Monday, August 25, 2008

[Bash] How to rename or copy multiple files based on part of the filename

I've been in projects where jsp filenames contained locale information, for example: "_en_GB.jsp".
In some cases I had to change this filename or copy the file to a different locale (da_DK), and instead of doing this manually on 10000s of files I created the following script to do the task for me.

Copy instead of renaming file
If you need to copy the files instead of renaming, eg. create a new file "testfile_da_DK.jsp" from the old testfile_en_GB.jsp, change the following line:

mv $i $newfile

to:

cp $i $newfile

You can use this as a script by copying the code below into a new file ".sh" and then run the script using "sh .sh" (requires the permissions to be set correctly using "chmod u+x .sh").


#!/bin/bash
echo "#############################################################"
echo "This script will locate files with a name that contains a "
echo "specific string. The string in the name of the file will then "
echo "be replaced with another specified string".
echo ""
echo ""
echo "Please write the string that identifies the name (or part of "
echo "the name) of the files you wish to rename, example: da_DK: "
echo ""
read -e FILE_STRING

echo ""
echo "Please write the string that should replace [$FILE_STRING] in the "
echo "filename, example en_GB: "
echo ""
read -e REPLACE_STRING

echo "Searching....."
echo ""

for i in `find . -name "*$FILE_STRING*"`
do
echo -n "---------- Parsing file [$i] .... "
SED_STRING="s/$FILE_STRING/$REPLACE_STRING/g"
newfile=`echo $i | sed -e $SED_STRING`
mv $i $newfile
echo " Done! ----------"
done;

echo "#############################################################"

No comments: