Remove hyphens from filename with Bash

2019-04-17 12:10发布

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

3条回答
可以哭但决不认输i
2楼-- · 2019-04-17 12:32
f=CropDamageVO-041412.mpg
echo ${f/-/}

or, of course,

mv $f ${f/-/}
查看更多
聊天终结者
3楼-- · 2019-04-17 12:36

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.

查看更多
一夜七次
4楼-- · 2019-04-17 12:40
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
查看更多
登录 后发表回答