0

Suppose I have a string like this

<start><a></a><a></a><a></a></start>

I want to replace values inside <start></start> like this

<start><ab></ab><ab></ab><ab></ab><more></more><vale></value></start>

How do I do this using Sed?

4 Answers 4

1

Try this :

sed 's@<start>.*</start>@<start><ab></ab><ab></ab><ab></ab></start>@' file
Sign up to request clarification or add additional context in comments.

Comments

0

I get this line with gnu sed :

sed -r 's#(<start>)(.*)(</start>)#echo "\1"$(echo "\2"\|sed  "s:a>:ab>:g")"\3"#ge'  

see example:

kent$  echo "<start><a></a><a></a><a></a><foo></foo><bar></bar></start>"|sed -r 's#(<start>)(.*)(</start>)#echo "\1"$(echo "\2"\|sed  "s:a>:ab>:g")"\3"#ge'                 
<start><ab></ab><ab></ab><ab></ab><foo></foo><bar></bar></start>

note

this will replace the tags between <start>s which ending with a . which worked for your example. but if you have <aaa></aaa>:

you could do: (I break it into lines for better reading)

sed -r 's#(<start>)(.*)(</start>)
 #echo "\1"$(echo "\2"\|sed "s:<a>:<ab>:g;s:</a>:</ab>:g")"\3"
 #ge' 

e.g.

kent$  echo "<start><a></a><a></a><a></a><aaa></aaa><aba></aba></start>" \
 |sed -r 's#(<start>)(.*)(</start>)#echo "\1"$(echo "\2"\|sed  "s:<a>:<ab>:g;s:</a>:</ab>:g")"\3"#ge'
<start><ab></ab><ab></ab><ab></ab><aaa></aaa><aba></aba></start>

Comments

0

sed 's/(\<\/?)a\>/\1ab\>/g' yourfile, though that would get <a></a> that was outside <start> as well...

3 Comments

not only <a></a> outside <start> but also tags like <ha></ha> or <bla></bla>...
I think I fixed it, but backreferences aren't something I normally use, so might be wrong.
If you are not sure, then put it explicitly to the answer.
0

grep -rl 'abc' a.txt | xargs sed -i 's/abc/def/g'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.