MYSYSAD.COM

Add String to Filenames Using an Inline For Loop

· Shell & text · Files & disks

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
or
# ls *.specific_extension_1 *.specific_extension_2 *.specific_extension_3 > mylist

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