Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

sed string substitution - keeping a double quote 1

Status
Not open for further replies.

gawker

Programmer
Feb 21, 2002
34
US
Hi,

I am working on a script, part of which does a string replacement. The user needs the ability to:

01) Enter a string that optionally contains embedded spaces.
02) Enter a string that optionally contains a double quote.

The following works just fine for (01):

Example: Change occurances of Oldstuff to NEW text

sed s/""Oldstuff"/""NEW text""/ /home/guest/tmp/old.dat > /home/guest/new.dat

The problem I am having is in getting the correct combination of double quotes (or whatever) characters to permit the final string to optionally maintain a double quote around the replaced data.

Example: Change occurances of Oldstuff to "NEW text" where the data is embraced by a double quote on each end.

I've tried a bunch of things without success.

Any ideas?

Thank you,

gawker


"Once the landslide has begun, it is too late for the pebbles to vote." Kosh, B5
 
The user will have to know that spaces can be include in one the strings by using double quotes or single quotes around the pattern. To have double quotes in the pattern just have them surround the pattern with single quotes. In you script save these patterns to variables.

STRING1=$1
STRING2=$2

and run sed as

sed "s/${STRING1}/${STRING2}/"

If you try and mix up the single and double quotes then trouble is likely.

I hope this helps,
ND
 
Hi bigoldbulldog,

I tried your suggestion in my script, where the user enters data at a command prompt. This data is then used by an awk process that does the sed replacement. The quotes are still eliminated.

Next, I tried something very basic at the command prompt:

$ n1="ghi";n2=""abx""
$ sed "s/${n1}/${n2}/" /home/guest/temp1/old.dat > /home/guest/new.dat

Again, the quotes were eliminated, leaving abx not "abx" in the file. I've also tried with three and four double quotes and got the same results.

Any ideas on what I may be doing wrong?

Regards,

gawker


 
Hi -

I'm suggesting you try

$ n1='ghi';n2='"abx"'
$ sed "s/${n1}/${n2}/" /home/guest/temp1/old.dat > /home/guest/new.dat

The double quotes on the outside should include the double-quotes within - and any space characters. You could also do
similar on the command line.

my_script 'ghi' '"abx"' /home/guest/temp1/old.cat > /home/guest/new.dat

I hope this works now,
ND
 
Thank you [smile].

Using the single quote/double quote combination worked.

Regards,

gawker
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top