Thursday, May 10, 2007

Add String to Filenames Using an Inline For Loop

A friend of mine had about 500 files in a directory. Based on specific extensions, he wanted roughly 300 of them to have a prepended string attached. An inline script was used to accomplish the task. Here is a simple example.

Here is the busy work part
# ls *.specific_extension_1 > mylist
# ls *.specific_extension_2 >> mylist
# ls *.specific_extension_3 >> mylist
# ls *.specific_extension_1 *.specific_extension_2 *.specific_extension_3 > mylist

Now for the inline for loop
# sh
# for filename in `cat mylist`
mv $filename PREPEND_STRING$filename
echo $filename changed | tee -a /tmp/logfile


Chad Mynhier said...

There's no need to do the busy work. Just do "for filename in *.foo *.bar *.baz".

esofthub said...

I mostly wanted to show the `cat filelist`.

As always, readers' comments make this blog more useful to the community. Thanks Chad.

JamesIsIn said...

With the aid of this post and a little other research I was able to solve my batch renaming problem:

Thanks for the assistance.