使用 Bash 从文件名中删除连字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10158704/
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
Remove hyphens from filename with Bash
提问by idoperceive
I am trying to create a small Bash script to remove hyphens from a filename. For example, I want to rename:
我正在尝试创建一个小的 Bash 脚本来从文件名中删除连字符。例如,我想重命名:
CropDamageVO-041412.mpg
CropDamageVO-041412.mpg
to
到
CropDamageVO041412.mpg
CropDamageVO041412.mpg
I'm new to Bash, so be gentle :] Thank you for any help
我是 Bash 的新手,所以要温柔:] 谢谢你的帮助
回答by Tim Pote
Try this:
尝试这个:
for file in $(find dirWithDashedFiles -type f -iname '*-*'); do
mv $file ${file//-/}
done
That's assuming that your directories don't have dashes in the name. That would break this.
那是假设您的目录名称中没有破折号。那会打破这个。
The ${varname//regex/replacementText}syntax is explained here. Just search for substring replacement.
该${varname//regex/replacementText}语法解释这里。只需搜索子字符串替换即可。
Also, this would break if your directories or filenames have spaces in them. If you have spaces in your filenames, you should use this:
此外,如果您的目录或文件名中有空格,这会中断。如果你的文件名中有空格,你应该使用这个:
for file in *-*; do
mv $file "${file//-/}"
done
This has the disadvantage of having to be run in every directory that contains files you want to change, but, like I said, it's a little more robust.
这样做的缺点是必须在包含要更改的文件的每个目录中运行,但是,就像我说的那样,它更健壮一些。
回答by jimw
FN=CropDamageVO-041412.mpg
mv $FN `echo $FN | sed -e 's/-//g'`
The backticks (``) tell bash to run the command inside them and use the output of that command in the expression. The sed part applies a regular expression to remove the hyphens from the filename.
反引号 (``) 告诉 bash 在其中运行命令并在表达式中使用该命令的输出。sed 部分应用正则表达式从文件名中删除连字符。
Or to do this to all files in the current directory matching a certain pattern:
或者对当前目录中匹配特定模式的所有文件执行此操作:
for i in *VO-*.mpg
do
mv $i `echo $i | sed -e 's/-//g'`
done
回答by DigitalRoss
f=CropDamageVO-041412.mpg
echo ${f/-/}
or, of course,
或者,当然,
mv $f ${f/-/}

