Files not renaming with rename command

2020-05-09 17:16发布

I have 3 files in my current working directory as follows:

abc def xyz.tgz
ghi jkl xyz.tgz
def klm zxc.tgz

I wish to rename the files such that the spaces should be replaced with an underscore. To achieve this I used the following approach:

rename -v 's/\ /_/g' *tgz

Following are the issues:

  1. The command executes without any error, but no files are renamed.
  2. When the directory contains only one tgz file, an error is observed as follows:

    rename: not enough arguments
    
  3. If I use the following:

    rename " " "_" *.tgz
    

    Only one occurrence of space is replaced with an underscore.

2条回答
乱世女痞
2楼-- · 2020-05-09 17:47

This code will find all files or directories in the current directory and replace all spaces in their filenames with underscores:

find . -name '* *' -exec bash -c 'mv -v "$0" "`echo $0 | tr " " "_"`"' {} \;
查看更多
可以哭但决不认输i
3楼-- · 2020-05-09 17:50

Your system seems to provide the other rename, which doesn't support Perl's substitution. You can still use it:

while ls *' '*tgz &> /dev/null ; do
    rename ' ' _  *' '*tgz || break
done

Or just use mv with parameter expansion:

for file in *' '*tgz ; do
    mv "$file" "${file// /_}"
done
查看更多
登录 后发表回答