Sed prints several lines instead of matching group

61 views Asked by At

I have got the xml file, for example:

<configuration>
  <property>
    <name>prop_name</name>
    <value>prop_value</value>
  </property>
</configuration>

I want to print the value of the property ("prop_value" in this example). I know that sed is not the best solution for this issue but I am forced to use bash :((

I was trying to use the next construction:

sed -n '/prop_name/{:a;N;/<\/value>/!ba {s|<value>\(.*\)</value>|\1|p}}' file

But what I have got is:

<name>prop_name</name>
prop_value

It prints every line in pattern space even if it is not matched. Is it possible to remove the first line from sed's pattern space and print only the matched group? Thank everyone in advance for the help.

1

There are 1 answers

1
Wiktor Stribiżew On BEST ANSWER

You forgot to match all the data you have before the <value> that you kept in the pattern space with N command, add .* before the <value>:

sed -n '/prop_name/{:a;N;/<\/value>/!ba {s|.*<value>\(.*\)</value>|\1|p}}'
#                                          ^^

See the online sed demo:

s='<configuration>
  <property>
    <name>prop_name</name>
    <value>prop_value</value>
  </property>
</configuration>'
sed -n '/prop_name/{:a;N;/<\/value>/!ba {s|.*<value>\(.*\)</value>|\1|p}}' <<< "$s"
# => prop_value