I am trying to convert



<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?


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.

  • 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

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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