Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I am trying to convert

<id>1</id>
<Name>ENTERPRISE RESOURCE PLANNING</Name>

to:

<column name="id">1</column>
<column name="Name">ENTERPRISE RESOURCE PLANNING</column>

I am assuming the best tool for the job would be sed, however I can't figure out how to keep parts of the original text in the replace part.

If I do:

$ sed -i 's/<.*>.*<.*>/<column name="\\1">\\2<\/column>/g' filename.xml

The output is:

<column name="\1">\2</column>
<column name="\1">\2</column>

Or doing similar from within vi, it outputs:

<column name=""></column>
<column name=""></column>

How can I make it so that \1 and \2 are substituted back to their original values?

share|improve this question

1 Answer 1

up vote 12 down vote accepted

You can use groups, e.g.:

$ sed -i 's/<\(.*\)>\(.*\)<.*>/<column name="\1">\2<\/column>/g' filename.xml

Probably the most confusing part about REs is that there are various syntactic flavors.

For example sed and vim use basic regular expressions where you have to quote () to get their meta-meaning.

With extended regular expressions (e.g. awk, egrep and less) you have to quote () to get the literal meaning. There are similar differences for other meta-characters.

The rationale behind BRE () semantics is that when most of your input is C-Code then it is more practical to have to quote parentheses for meta-use.

share|improve this answer
    
This was actually the first thing I tried, but I didn't escape the ( and ) characters. Stupid question, but why is that necessary? –  Mike Sep 14 '11 at 19:12
1  
@Mike, good question - updated the answer. –  maxschlepzig Sep 14 '11 at 19:30

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.