Linux Blog

Bash Script Renaming Files

Filed under: Shell Script Sundays — at 3:15 am on Sunday, February 6, 2011

I recently needed to rename a bunch of files. I didn’t want to do it manually because it would take too long and I don’t like copying+pasting that many times. This is where shell-scripting comes in handy.

Lets take this example (its not exactly what I was doing but will work for this context.) I wanted the type to show up last in the following example:

ls -1
Cola - Amazing Things to do with cola.txt
Beer - Brewing your own Microbrews.txt
Wine - The connoisseurs guide.txt

To look like:

Amazing Things to do with cola - Cola.txt

To Achieve this the following can be done:

ls -1 | while read i; do mv "$i" "`echo $i | cut -d - -f 2 |cut -c 2- | sed 's/\.txt//'` - `echo $i | cut -d - -f 1`"; done;

This will give the order I want but without the .txt on the end. The next thing to do is to append the .txt.

For some odd reason there was a space on the end so I compensated by using “$i “. The following adds .txt to the end of each file:

find . | while read i; do mv "$i " "$i.txt"; done;

For more examples on how to use the commands used in this post refer to the man pages and related posts.