Remove white space from file name and rename it with bash command

Some Linux tools does not properly work with files which include spaces in their names. This simple bash for loop will remove white space from file names and rename/move for all files in the given directory.

First enter directory with cd:

cd /my/directory

and then run:

for f in *; do mv "$f" `echo $f | tr ' ' '_'`; done

4 Responses

  1. Google is great, but would be nothing without you! Thanks for the awesome tip.

  2. Thank you for posting this bit of code. I’ve been having all sorts of problems with a bash script today only to find out it was because the file names contained white spaces. This script of yours completely fixed my problem.

  3. I was in the same problem. Just remember John, its a bash command not a script. I do the aclaration because I was confused once about scripts and commands. Thanx linuxconfig!!

  4. Actually, it’s not even a bash command, as the same exact code will work in a vanilla Bourne shell. If there’s one thing that irks me about some Linux users, it’s assuming all shell scripting is bash scripting. There are other shells out there, some older than bash.

    I’d like to see if there’s a way to modify this to be more specific. For example, only change the spaces to underscores for all files matching N*

    Very nice as it is, though. Thanks!

Leave a Reply