This is a rough version of a script I am using at work. It is a search and replace script which will change all instances of one string with another in all the files in a particular directory. I am currently using it to edit SQL scripts. Newer versions of certain tables come up, and I needed an easy way to change select foo from this_table where … ” to “ select foo from that_table where … “.
If my Perl kung foo was stronger, I think it would be easier to write the script in Perl. As it stands, my Unix scripting is somewhat stronger. One complaint I currently have is that the Korn shell is different enough from the Bash shell that the syntax is enough to trip me up on simple things.
Without further ado, here is the code- please improve and comment upon:
#!/bin/ksh
# danny anderson
# sed magic monster 12.07.2004
# swaps all instances of OLD line from all files in the target directory
# with NEW line
# usage: "sed_monster (target dir)
# where target dir holds only the files that should be changed. If no
# target is specified on the command line, assume currently directory
# backup files to be changed in datestamped subdirectory
backup_dir="$1/sed_originals_`date '+%Y%m%d'`_`date '+%H%M'`"
echo "making backup directory: " $backup_dir
mkdir $backup_dir
# prompt the user for the old string & the replacement string
echo "OLD LINE: ";
read old_line
echo "NEW LINE: ";
read new_line
# loop through all the files in the target dir
for filename in ${1:+$1/}* ;
do
cp $filename $backup_dir
sed -e 's/'"$old_line"'/'"$new_line"'/g' $filename > $filename.new
mv $filename.new $filename
done
I’m no expert, but I don’t think I can improve on it. Awk and sed are easily the biggest hammers in the toolbox if you ask me. I think there’s an O’Reilley book on awk and sed that’s about as big as a phone book, which is pretty impressive when you think about how powerful two simple Unix commands can be.