Monday, August 1, 2011

How do I convert spaces to underscores in file names and directory names on Linux?

Have you ever wanted to change all the spaces to underscores in a directory?  After going through various methods, the following is the most reliable way that I have found for bash users. Note, that there are many ways to accomplish this task. These examples should be typed in as a single line:

find . -depth -maxdepth 1 -name "* *" -exec sh -c 'mv "${0}" "${0// /_}"' {} \;

Note that '-maxdepth 1' changes spaces to underscores for files, directories, and links in the current directory. Changing that number to 2 or more will change spaces to underscores two or more levels deep in the current file system tree in addition to the current directory. Leaving out -maxdepth 1 will change spaces to underscores in the entire tree.

Note also that the '.' means start in the current directory. You can certainly put other paths in place of the dot.  You can even put what is called a globbing pattern:

find music* -depth -maxdepth 1 -name "* *" -exec sh -c 'mv "${0}" "${0// /_}"' {} \;

will process only files, directories, and links that begin with music.