Shell – How to rename all files with special characters and spaces in a directory

linuxrenameshell-script

How can i rename all the files in a specific directory where the files contains blanks spaces and special characters ($ and @) in their names?

I tried the rename command as follows to replace all the spaces and special characters with a _:

$ ls -lrt
total 464
-rwxr-xr-x. 1 pmautoamtion pmautoamtion 471106 Jul 17 13:14 Bharti Blocked TRX Report Morning$AP@20150716.csv


$ rename -n 's/ |\$|@/_/g' *
$ ls -lrt
total 464
-rwxr-xr-x. 1 pmautoamtion pmautoamtion 471106 Jul 17 13:14 Bharti Blocked TRX Report Morning$AP@20150716.csv
$

The command works but won't make any changes in the file names and won't return any error as well. How can in fix this and are there other ways as well?

Best Answer

The -n flag is for

--no-act

No Action: show what files would have been renamed.

So it's normal if you don't have any changes.

Regarding your command, it's working for me:

$ touch "a @ test"
$ ls
a @ test
$ rename -n 's/ |\$|@/_/g' *
a @ test renamed as a___test

Maybe depending on your shell, you have to escape the |

$ rename -n 's/ \|\$\|@/_/g' *

Or you can use the […] notation to group characters:

$ rename -n 's/[ @\$]/_/g' *
Related Question