Dec 6, 2011

Iterative Perl and Bash search and replace words in multiple files at once


Learning the ropes around applying Perl magic to mundane chores.

-e: tells perl to treat the line that follow as a perl script.

': wrap the line of code in single quotes to prevent perl from attempting to interpret special characters. However \' causes problems and is never printed literally even if escaped with a \ and enclosed in single quotes. I still don't know the workaround to this quirk.

-p: causes Perl to assume the following loop around your program, which makes it iterate over filename arguments.

-pe: p and e combined over a line of code iterates over every file on the command line or on the text fed to it on STDIN

-i: lets you edit files in place.

s/oldstring: Searches for the following old string.

/newstring/g: Does a global replace of the old string with the new string.


So the mass search and replace command would look like


perl -pi.orig -e 's/oldstring/newstring/g' filename


Though this works in a directory, somehow it doesn't iterative work in the sub-directories. So it's time fore bash script.

#!/bin/sh
# tells the interpreter to use the shell for interpreting these following commmands

# Use grep to find the files with the string of interest
for file in $(grep -il "oldstring" *.tex)
# Start bash script
do
# give the file list to sed
# search and replace (same as perl above)
# sed doesn't mess with originals so write the file with changes to a temporary file
sed -e "s/oldstring/newstring/ig" $file > /tmp/tempfile.tmp
# Move the temporary file created to the file list that you created in the grep step
# The new file list will have replaced strings
mv /tmp/tempfile.tmp $file
done

0 Comments:

Post a Comment