Operating System - HP-UX
1834408 Members
1877 Online
110067 Solutions
New Discussion

Re: Search and replace a string inside a shell script

 
chinnaga
Advisor

Search and replace a string inside a shell script

Hi,

I want to write a shell script which would search and replace a sting for the list of files. I tried using sed inside the shell script, but it doesn't seem to work. could you pls help me with this.
3 REPLIES 3
AwadheshPandey
Honored Contributor

Re: Search and replace a string inside a shell script

#!/bin/bash # This script will search and replace all regular files for a string # supplied by the user and replace it with another string. # # Written by Daniel McCarthy # daniel.mccarthy@linuxphile.org # function usage { echo "" echo "Search/replace script" echo " Written by Daniel McCarthy" echo " daniel.mccarthy@linuxphile.org" echo " http://linuxphile.org" echo "" echo "Not enough parameters provided." echo "Usage: ./$0 searchstring replacestring" echo "Remember to escape any special characters in the searchstring or the replacestring" echo "" } #check for required parameters if [ ${#1} -gt 0 ] && [ ${#2} -gt 0 ]; then for f in `find -type f`; do if grep -q $1 $f; then cp $f $f.bak echo "The string $1 will be replaced with $2 in $f" sed s/$1/$2/g < $f.bak > $f rm $f.bak fi done else #print usage informamtion usagefi
It's kind of fun to do the impossible
Arturo Galbiati
Esteemed Contributor

Re: Search and replace a string inside a shell script

Hi,
see the atthaced script.

HTH,
Art
chinnaga
Advisor

Re: Search and replace a string inside a shell script

Hi Guys,

Thanks a lot, it was really helpfull.