As a DBA, regardless of RDBMS type, you will come across the need to replace text strings in dozens if not hundreds of files to facilitate the completion of your job. In this article we will cover the use of bash and perl scripts to perform text replacement of multiple files within a UNIX or LINUX environment.
1. Logon to your UNIX or LINUX server as the owner of the files you want to update or a user which has permission to update these files.
2. In this procedure we will create a file named files.txt containing a listing of all files we wish to update.
mylinux:> more files.txt
./test1.txt
./test2.txt
./test3.txt
./test4.txt
3. Next create a file called update.sh with the following text.
dt=`date “+%m%d%Y”` # Gets current date.
cat ./files.txt|while read line # Reads in all files from files.txt one line at a time.
do # Opens a loop
cp $line $line$dt # copies original file to backup with file_name+date.
ls $line |xargs perl -pi -e ‘s/{old_string}/{new_string}/g’ # if found replace old_string with new_stirng
done # ends loop
4. Change permissions on the update.sh to 770, so it will execute.
mylinx:>:>chmod 770 update.sh
mylinx:>:>
5. View the contents of one of the files in you files.txt file.
mylinx:>:>cat test*
one
one
one
one
mylinx:>:>
6. In this example, all of the files contain the text “one” which we will replace with the string “two”. Thus your update.sh file will look like the example below.
dt=`date “+%m%d%Y”`
cat ./files.txt|while read line
do
cp $line $line$dt
ls $line |xargs perl -pi -e ‘s/one/two/g’
done
7. Execute the update.sh file with the command: ./update.sh.
mylinx:>:>./update.sh
mylinx:>:>
8. Now cat all files named test*
mylinx:>:>cat test*
two
two
two
two
mylinx:>
As you can see all strings of “one” have been replaced with the string “two”. This completes replacement of strings in UNIX and LINUX.
Larry Catt, OCP 9i, 10g
oracle@allcompute.com
www.allcompute.com