Wednesday, September 19, 2007

Joining and Renaming Multiple Files Using a for loop

I'm doing this personal project where I parsed almost 26,000 items into a particular format. I then parsed 300 of those items into file with a unique filename, so I ended up with 86 unique files. Lastly, I added a header and footer to each unique file and then renamed it to its original filename. Here is a pithy example of what was done on this task.

# sh
# for i in `ls *_num_*`
do
cat header $i footer > $i.$$
mv $i.$$ $i
echo $i done
done

Extra: For those that asked me how to rename files, the mv command is used to rename files in UNIX. In the example below, the esofthub filename will be renamed to esoft
e.g. # mv esofthub esoft

3 comments:

Justin said...

the ls isn't needed

for i in *_num_*

esofthub said...

justin, good point.

Anonymous said...

The bourne shell `cmd` is depreciated, AFAIK you should use $(cmd) instead.