Rename files in bash via string handling

Sep 07, '06 07:30:05AM

Contributed by: Just Fred

I periodically receive files that are somewhat cryptically named, and I like to rename them to something more understandable. I found this older hint, but it didn't work for my needs -- my renamed files contain spaces. For example, I might receive several files whose names are something like this:

TS_412_96k.fil
TS_413_96k.fil
TS_414_32k.fil
And I want to rename them something like:
Total Entry #412.txt
Total Entry #413.txt
Total Entry #414.txt
After nearly tearing my hair out trying various combinations of awk and sed in my scripts, I discovered that the bash shell has its own string handling functions! This quickly allowed me create the following simple script:
for prog in *.fil; do
    progno=${prog:3:3}
    mv $prog 'Total Entry #'$progno'.txt'
done
Voila! Note that bash starts character numbering at zero rather than one, as do awk and sed. Thus, in the example above, the substring returned by {prog:3:3} would be the numeric values in the original filenames.

Comments (12)


Mac OS X Hints
http://hints.macworld.com/article.php?story=20060905135507309