bash 如何从 Unix shell 脚本中的字符串中删除字符?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19216469/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 08:12:03  来源:igfitidea点击:

How do I remove a character from a string in a Unix shell script?

bashshellunix

提问by Generalkidd

I have several files that are named like this: file - name.txt

我有几个这样命名的文件:file - name.txt

How do I remove the " - " using a bash script in UNIX from all the files?

如何在 UNIX 中使用 bash 脚本从所有文件中删除“-”?

采纳答案by kojiro

Use parameter expansion to remove the part of the string you want to be rid of. Make sure to use double-quotes to prevent mvfrom misinterpreting input.

使用参数扩展来删除要删除的字符串部分。确保使用双引号以防止mv误解输入。

for i in ./*' - '*; do
    mv "$i" "${i// - }"
done

回答by Eran Ben-Natan

If I understand correctly, try rename ' - ' '' *

如果我理解正确,请尝试 rename ' - ' '' *

回答by elimirks

Sed it up!

塞起来!

# Iterate each file in the current directory.
for i in *; do
  # Move the file to the new filename, replacing ' - ' with '_'
  mv "$i" `echo $i | sed 's/ - /_/g'`
done