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

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' *

You could try like this:

for file in ./*Block*                                       
do echo mv "$file" "${file//[ ()@$]/_}"
done

If you're happy with the result, remove the echo before mv to actually rename the files.


looking for a handsome script to remove special characters as well as german special characters, replacing them with universal ones to not remove useful information I've updated the last version of the script which had some minor issues resulting in:

#!/bin/bash

for file in ./*
do
  infile=`echo "${file:2}"|sed  \
         -e 's|"\"|"\\"|g' \
         -e 's| |\ |g' -e 's|!|\!|g' \
         -e 's|@|\@|g' -e 's|*|\*|g' \
         -e 's|&|\&|g' -e 's|]|\]|g' \
         -e 's|}|\}|g' -e 's|"|\"|g' \
         -e 's|,|\,|g' -e 's|?|\?|g' \
         -e 's|=|\=|g'  `
  outfileNOSPECIALS=`echo "${file:2}"|sed -e 's|[^A-Za-z0-9._-]|_|g'`
  outfileNOoe=`echo $outfileNOSPECIALS| sed -e 's|ö|oe|g'`
  outfileNOae=`echo $outfileNOoe| sed -e 's|ä|ae|g'`
  outfileNOue=`echo $outfileNOae| sed -e 's|ü|ue|g'`
  outfileNOOE=`echo $outfileNOue| sed -e 's|Ö|OE|g'`
  outfileNOAE=`echo $outfileNOOE| sed -e 's|Ä|AE|g'`
  outfileNOUE=`echo $outfileNOAE| sed -e 's|Ü|UE|g'`
  outfileNOss=`echo $outfileNOUE| sed -e 's|ß|ss|g'`
  outfile=${outfileNOss}
  if [ "$infile" != "${outfile}" ]
  then
        echo "filename changed for " $infile " in " $outfile
        mv "$infile" ${outfile}
  fi
done

exit

resulting in:

enter image description here

@don_crissti: He's doing the hokus-pokus with the infile since linux would have it's own issues with handling special characters when moving the filename.