Aug 27, 2011
Jason

How to rename multiple files in Linux

From time to time, we may need to rename multiple files in Linux. It is quite frustrating to find out that mv old_name* new_name* is not working actually.

So after a few trials and errors, I’ve got the following script, which is really time saver for me.

This is what my files look like before the script.

$ ls -lth
total 12K
-rw-r–r– 1 username group 6 Aug 26 01:38 old_name_3.txt
-rw-r–r– 1 username group 6 Aug 26 01:38 old_name_2.txt
-rw-r–r– 1 username group 5 Aug 26 01:38 old_name_1.txt

I want to rename all those old_name to new_name. Here is the script to do that:

$ for nn in `ls -1 old*`; do NAME=`echo $nn | sed -e ‘s/^old_name/new_name/g’`; mv $nn $NAME; done

This is the aftermath.

$ ls -lth
total 12K
-rw-r–r– 1 username group 6 Aug 26 01:38 new_name_3.txt
-rw-r–r– 1 username group 6 Aug 26 01:38 new_name_2.txt
-rw-r–r– 1 username group 5 Aug 26 01:38 new_name_1.txt

I hope this script will be helpful for you as well. As always, feel free to leave a comment if you need any help.

Tags:

No related posts.

Leave a comment