Sometimes while working on project you may need to do few changes in string(s)/text(s) on your working files like comments blocks, file headers, date etc. Following Shell script will help you to replace strings and texts under its directory and subdirectory using Sed editor. But before implementing this you must need to aware with Sed editor and how to use it.
Introduction to Sed
Sed is a special editor for modifying files automatically. If you want to write a program to make changes in a file, sed is the tool to use. To know more about its syntax, commands and how to use it please check this link : http://www.grymoire.com/Unix/Sed.html or just google "Sed".
Example
#!/bin/sh # Shell script to search and replace number of string(s) or text(s) from file under its directory and subdirectory. MYDIR="your_directory_name/" show_files() { if !(test -d "$1") then return; fi cd "$1" echo "$1"; #Show Directory name for i in * do if test -d "$i" #if directory then show_files "$i" #recursively list files cd .. else sed -i 's/HelloWorld/Welcome/g;' $i; sed -i 's/refer to http:\/\/www.oldsite.com/contact http:\/\/www.newsite.com/g;' $i; sed -i 's/HelloWorld/Welcome/g;' $i; sed -i 's/Helloworld/Welcome/g;' $i; sed -i 's/2007\-2013/2013/g;' $i sed -i 's/@oldsite/@newsite/g;' $i; sed -i 's/oldprefix_/newprefix_/g;' $i; echo "$i"; #Display File name fi done } if [ $# -eq 0 ] then show_files "$MYDIR" exit 0 fi for i in $* do MYDIR="$1" show_files "$MYDIR" shift 1 #To read next directory/file name done
Thanks. Hope it'll help you.
No comments:
Post a Comment