Remove hyphens from filename with Bash

江枫思渺然 提交于 2019-12-12 09:24:50

问题


I am trying to create a small Bash script to remove hyphens from a filename. For example, I want to rename:

CropDamageVO-041412.mpg

to

CropDamageVO041412.mpg

I'm new to Bash, so be gentle :] Thank you for any help


回答1:


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.

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.




回答2:


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.

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



回答3:


f=CropDamageVO-041412.mpg
echo ${f/-/}

or, of course,

mv $f ${f/-/}


来源:https://stackoverflow.com/questions/10158704/remove-hyphens-from-filename-with-bash

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!