My friend today asked me how to convert all spaces in filenames under a specified directory to underscores. Also, at the same time lowercase all of the filenames. Here is a quick script to do what is needed. Let us start with creating some test data in a temp directory:
touch Foo FooO "Foo Bar" "FOO BAaR"
\ls | while read -r FILENAME
mv -v "$FILENAME" `echo $FILENAME| tr ' ' '_'| tr '[A-Z]' '[a-z]'`
Note:Â I intentionally have slash in front of ls (\ls).Â \ls means that we want to make sure there is no ls alias overwriting our command. This is needed if your system has alias setup to display ls in a different way instead of default listing.Â mv -v shows us the filenames being renamed as your script goes through the whole dir.Â Your output should be like:
`Foo' -> `foo'
`FOO BAaR' -> `foo_baar'
`Foo Bar' -> `foo_bar'
`FooO' -> `fooo'
One of the very powerful commands in this post is the “tr” command. This command is not as popular as sed or awk but it is very useful and simple to use (read more about tr).
If you only needed to convert spaces to underscores and you are using CentOS/Fedora/Redhat, you can use this simpler method. NOTE: this command is not available on all distributions:
rename " " "_" *
Learn more about rename command
DISCLAIMER: Please be smart and use code found on internet carefully. Make backups often. And yeah.. last but not least.. I am not responsible for any damage caused by this posting. Use at your own risk.