Files not renaming with rename command

2020-05-09 17:57发布

问题:

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.

回答1:

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


回答2:

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 " " "_"`"' {} \;