Monday, April 14, 2014

Change a String in All Files in a Directory 

The script shown in this section does a search and replace in all files in a directory, replacing one
string with another and making a backup of the original files. The for loop that you see in the script causes the sed command to be executed for each file in the current directory. The sed command does the actual search and replace work, and at the same time it writes the new versions of any affected files to a temporary directory.

>cat chg_all.sh
 #!/bin/ksh
 tmpdir=tmp.$$
 mkdir $tmpdir.new
 for f in $*
do
  sed -e 's/oldstring/newstring/g'\
 < $f > $tmpdir.new/$f
done

# Make a backup first!
mkdir $tmpdir.old
mv $* $tmpdir.old/
cd $tmpdir.new
mv $* ../

cd ..
rmdir $tmpdir.new

When executing this script, pass in a file mask as an argument. For example, to change only SQL
files, the command would be executed like this:

root>chg_all.sh *.sql

The command in this example causes the string oldstring to be changed to newstring in all .sql files
in the current working directory. Remember that the strings to be changed are specified in the script, while the file mask is passed as a parameter. I don't pass the old and new strings as parameters
because the sed command can be quite tricky, especially if your strings contain special characters.
The sed command that you see in the script invokes the "string editor" for Unix.

The sed command always makes a copy of the changed files, and it never changes a file in-place. Hence, you see in this example that the sed command writes new versions of all changed files to the $tmpdir.new directory. The changes are actually made using sed before the backup copies are made. However, the new
versions of the files are not copied back from $tmpdir.new until after the old versions have been
copied to the backup directory. 

No comments:

Post a Comment