Operating System - HP-UX
1832864 Members
2833 Online
110048 Solutions
New Discussion

Re: Replace string in file

 
chandregowda
Advisor

Replace string in file

Hi,
My file "test" contains /abc/efg/qwerty

and my variables a and b contains
a=/abc/efg
b=/qwerty
how can i repace the contents of my file
"testt" with #/abc/efg/qwerty using a and b variables
7 REPLIES 7
Steven E. Protter
Exalted Contributor

Re: Replace string in file

Shalom

sed is a good tool

http://www.linuxquestions.org/questions/linux-newbie-8/does-anyone-know-of-a-bash-script-can-search-and-replace-txt-in-a-file.-278332/

http://forums11.itrc.hp.com/service/forums/questionanswer.do?threadId=57865

SEP
Steven E Protter
Owner of ISN Corporation
http://isnamerica.com
http://hpuxconsulting.com
Sponsor: http://hpux.ws
Twitter: http://twitter.com/hpuxlinux
Founder http://newdatacloud.com
Dennis Handly
Acclaimed Contributor

Re: Replace string in file

You can use sed(1):
a=/abc/efg
b=/qwerty
sed -e "s:\\($a$b\\):#\\1:" test > test.new
chandregowda
Advisor

Re: Replace string in file

Thanks dennis,
Appreciate your early help.
Its working fine.
chandregowda
Advisor

Re: Replace string in file

Dennis
wat is the use of \\ in
sed -e "s:\\($a$b\\):#\\1:" test > test.new
Dennis Handly
Acclaimed Contributor

Re: Replace string in file

>Appreciate your early help.

If our answers were helpful, please read the following about assigning points:
http://forums.itrc.hp.com/service/forums/helptips.do?#33


>what is the use of \\ in:
sed -e "s:\\($a$b\\):#\\1:" test > test.new

I assumed you didn't want to repeat $a$b twice and since you can use regular expressions to select pieces from the original string to add back in the replacement string, I used it. Ordinarily you would like to use '' for sed and not "". But because you want to use $a inside, you need "". If you need to use "\", you need to double them.

So your Regular Expression is:
s:\(stuff\):#\1:

This puts "stuff", delimited by \( and \), back where you have the \1, preceded by a "#". You can select multiple pieces and use \1, \2, to put them back, in any order you like.
chandregowda
Advisor

Re: Replace string in file

How can write same using AWK command

Regards,
gowda
Dennis Handly
Acclaimed Contributor

Re: Replace string in file

>How can write same using AWK command?

Since it is too hard to use "" with awk, you use -v to pass in a variable:
awk -v STR="$a$b" '
{
sub(STR, "#" STR)
print $0
}' text