July 2010
M T W T F S S
« Jun    
 1234
567891011
12131415161718
19202122232425
262728293031  
86

Categories

Archives

[one-liner]: Renaming a Set of Files in Bash

I do this command from time to time so I wanted to just jot it down so I didn’t have to go recreating every 6 months that I seem to need it. The setup for this example is that I had created a bunch of screenshots named ss#.png and I wanted to rename them to ss_centos5_raid_setup_#.png, where “#” is a numeric value.

Initial Set of Files
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# Here what the directory looks like to start
% ls
ss01.png
ss02.png
ss03.png
ss04.png
ss05.png
ss06.png
ss07.png
ss08.png
ss09.png
ss10.png
ss11.png
ss12.png
ss13.png
New File Names
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# and here's what our command will generate for new names
# NOTE: this instance of the command is for debug purposes only
#
% for old in *; do new="`echo $old | sed 's/ss/ss_centos5_raid_setup_/'`"; echo $new; done
ss_centos5_raid_setup_01.png
ss_centos5_raid_setup_02.png
ss_centos5_raid_setup_03.png
ss_centos5_raid_setup_04.png
ss_centos5_raid_setup_05.png
ss_centos5_raid_setup_06.png
ss_centos5_raid_setup_07.png
ss_centos5_raid_setup_08.png
ss_centos5_raid_setup_09.png
ss_centos5_raid_setup_10.png
ss_centos5_raid_setup_11.png
ss_centos5_raid_setup_12.png
ss_centos5_raid_setup_13.png
Moving $old to $new
1
2
# and here's the final command that will do all the lifting
for old in *; do new="`echo $old | sed 's/ss/ss_centos5_raid_setup_/'`"; mv $old $new; done
The general form of this command
1
for old in *; do new="`echo $old | sed 's/<old prefix>/<new prefix>/'`"; mv $old $new; done

NOTE: For further details regarding my one-liner blog posts, check out my one-liner style guide primer.

Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>