Chris
Chris

Reputation: 1019

changing value using sed in xml file

I want to change port in following input file:

<?xml version="1.0" encoding="utf-8"?>
<service>
  <short>SSH</short>
  <port protocol="tcp" port="22"/>
</service>

I tried following command without success:

sed "s|\("^[[:space:]]*.+port[[:space:]]+protocol=.+port="\).*|\1\"3022\"\/>|" inputfile

but it does no change.

When I grep -E it return correct line and high-light correct matching:

# grep -E '^[[:space:]]*.+port[[:space:]]+protocol=.+port=' inputfile
  <port protocol="tcp" port="22"/>

Why sed does not do the job?

Update: I found another command to achieve this:

sed -E '/short/,/service/  s/port=[^<]*/port=\"3022\"\/>/' inputfile

Upvotes: 0

Views: 118

Answers (1)

KamilCuk
KamilCuk

Reputation: 141010

Why sed does not do the job?

Because sed regex and grep regex are different, as to which characters you have to escape to get the same meaning. In sed + means literal +, I think you want:

sed 's|\(^[[:space:]]*.\+port[[:space:]]\+protocol=.\+port=\).*|\1"3022"/>|'

whereas in extended POSIX regular expression \( means literal (, wheres ( starts a group:

sed -E 's|(^[[:space:]]*.+port[[:space:]]+protocol=.+port=).*|\1"3022"/>|'

Note I also changed quoting from " to ' for easier escaping.

Upvotes: 2

Related Questions