Thursday, January 10, 2008

How to change multiple files into a progressive number order


I'm a big collector of pictures. I usually download pictures that my friends may post on Facebook or other sites for events that I was part of. For Facebook I use a Firefox add-on called Facebook Album Downloader. It will download all pictures for a specific album into your PC. But the problem is, that most of the times these pictures get renamed when uploaded. So you'll end up getting a really weird name for the pictures, which for me, being a freak at organizing my files just doesn't cut.

It's in times like this that I'm glad I use Linux. Here's a little script that will help me to change this.

Let's say I have the following files in my folder:

$ ls -1
fgthnt.txt
sadfasd.txt
sdfsdf.txt
tyhy.txt
ujtyuj.txt
ujyunyum.txt
wdfaw.txt
wertet.txt
werwert.txt
yjmyu.txt
yujjuj.txt


I would like to rename all these files to an organized manner. My pictures are usually named with numbers. I started doing this when I was learning web-design with my brother in law many years ago (never went trough with it thou).

To achieve such task we would run the following code:

E=1; for i in `ls *txt` ; do mv $i $E.txt ; E=$((E+1)); done
$ ls -1
10.txt
11.txt
1.txt
2.txt
3.txt
4.txt
5.txt
6.txt
7.txt
8.txt
9.txt


Breakdown of code:
E=1 - Set a variable of value 1
for i in `ls *.jpg` - Creates variable “i” with individual lines from the output of the command 'ls *.jpg'
do mv $i $E.jpg - Moves value from variable “i” to “E”
E=$((E+1)) - Adds a count of 1 to E, so next file with be E
done - Finalizes it

Another way of renaming files is using the “rename” program. Some Linux distros have it installed by default. The program can be used in similar way to sed. For example, the command below would remove all dashes from all mp3 files in the working folder:

rename 's/-//g' *mp3


Vic.

No comments: