Linux and Bash: Replace spaces with underscores in all filenames

I find it annoying to have file names with whitespace characters in them under Linux, because I mainly work in the shell (Bash in my case) and it always requires ugly escaping.

Here is my Bash solution to replace all spaces (‘ ‘) with underscores (‘_’) in all file and directory names in the current directory:


cd ~/path/to/dir_with_ugly_files/
for FILE in *; do mv "$FILE" "$(echo $FILE | sed -e 's/ /_/g')"; done

You will get warnings for file names which do not contain any spaces, you can ignore those. Also note that this solution is not recursive, i.e., it does not descend into sub directories.

Advertisements

About dfspspirit

PhD student in bioinformatics, interested in photography, level design, digital image manipulation, architecture and, of course, bioinformatics.
This entry was posted in bash, linux, tools and tagged , , , . Bookmark the permalink.

2 Responses to Linux and Bash: Replace spaces with underscores in all filenames

  1. brian says:

    Aloha, thanks for the info. Out of curiosity what does the “-e” flag do? The script seems to work without it.

  2. dfspspirit says:

    You are right, the -e flag is not required. I guess Perl confusion made me add it.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s