views:

55

answers:

4

Hello, I am facing the following problem.

Let's say I have a file, which contains something like this:

blah blah blah blah
more text
<tag1>something</tag1>
<tag2>something else</tag2>
blah blah meh whatever
foo bar

What I want to do is to replace all occurrences of tag1 with tag2, and all occurences of tag2 with tag1. However, I don't know how to do it, since if I'd use something like sed 's/tag1/tag2/g' and then sed 's/tag2/tag1/g', I'd end up with a file with just tag1's.

What I need is to "flip" the two tags.

Thanks in advance.

+2  A: 

can you go via some tag you know doesn't exist in the file? i.e.

sed 's/tag1/tag99/g' 
sed 's/tag2/tag1/g'
sed 's/tag99/tag2/g'
second
I thought about that, I guess I'll go with it, but is there a cleaner solution?
houbysoft
Instead of tag99 use tag1tag1, this will make sure you don't hit any existing tags.
Pumbaa80
A: 

Replace tag1 with something unique (tag3), then set tag2 to tag1, then set tag3 to tag2.

smdrager
+5  A: 

How about just adding a temporary tag for the first replacement. Something like this:

sed -e 's/tag1/temporarytag/g' -e 's/tag2/tag1/g' -e 's/temporarytag/tag2/g'
Gary
This is the best answer of the three so far since it does it in one call to `sed` and is a complete answer.
Dennis Williamson
Indeed. Accepting, thanks.
houbysoft
A: 
$ sed 's/tag1/tmp/g;s/tag2/tag1/g;s/tmp/tag2/g' file
ghostdog74