linux bash rename – How to Replace One Char with Another in All Filenames of the Current Directories?

bashlinuxrename

How do you rename all files/subdirs in the current folder?

Lets say, I have many files and subdirs that are with spaces and I want to replace all the spaces with an underscore.

File 1
File 2
File 3
Dir 1
Dir 3

should be renamed to

File_1
File_2
File_3
Dir_1
Dir_3

Best Answer

If you need to rename files in subdirectories as well, and your find supports the -execdir predicate, then you can do

find /search/path -depth -name '* *' \
    -execdir bash -c 'mv -- "$1" "${1// /_}"' bash {} \;

Thank to @glenn jackman for suggesting -depth option for find and to make me think.

Note that on some systems (including GNU/Linux ones), find may fail to find files whose name contains spaces and also sequences of bytes that don't form valid characters (typical with media files with names with non-ASCII characters encoded in a charset different from the locale's). Setting the locale to C (as in LC_ALL=C find...) would address the problem.

Related Question