Steve
Steve

Reputation: 8839

sed regex replace with quotes

Suppose I have a text file with many lines, one of them being this:

  <property name="HTTP_PORT" value="8080"></property>

And I want to change it to this with sed:

  <property name="HTTP_PORT" value="80"></property>

How would I go about that? I have tried a number of things including these:

sed 's/^\(.+\)value=\"8080\"\(.+\)$/\1value=\"80\"\2/g' config.xml
sed 's/^\(.+\)value="8080"\(.+\)$/\1value="80"\2/g' config.xml
sed 's/^\(.+\)8080(.+\)$/\180\2/g' config.xml
sed 's/^\(.+\)\"8080\"\(.+\)$/\1\"80\"\2/g' config.xml
sed 's/^\(.+\)"8080"\(.+\)$/\1"80"\2/g' config.xml

but all to no avail. The input and output are always the same.

Upvotes: 3

Views: 948

Answers (4)

potong
potong

Reputation: 58578

This might work for you:

sed -i '\|<property name="HTTP_PORT" value="8080"></property>|s/80//' config.xml

or perhaps:

sed -i 's/"8080"/"80"/' config.xml

Upvotes: 0

shellter
shellter

Reputation: 37318

Per corrections by @Kevin (Thanks!)

echo $'<property name="HTTP_PORT" value="8080"></property>'\
| sed 's/^\(.\+\)value=\"8080\"\(.\+\)$/\1value=\"80\"\2/g'

The correct fix is to escape the '.+' the plus sign to achieve '1 or more'.

Edited original answer (which shows an alternate solution to the problem) *so given the context you are using, what is wrong with the traditional .* (zero or more)*

echo $'<property name="HTTP_PORT" value="8080"></property>'\
| sed 's/^\(.*\)value=\"8080\"\(.*\)$/\1value=\"80\"\2/g'

** output **

<property name="HTTP_PORT" value="80"></property>

Also, +1 for anchoring your search targets with '^' and '$'. I have seen cases (similar to what you are doing), where NOT having the anchors greatly increases run time.

I hope this helps.

Upvotes: 1

Kevin
Kevin

Reputation: 56159

How about the direct translation of what you want:

sed 's|<property name="HTTP_PORT" value="8080"></property>|<property name="HTTP_PORT" value="80"></property>|g'

It's not as "clever" a solution as you or I could find, but it's as straightforward as they come and as you're looking for a static string, it's all you need.

Upvotes: 2

$> cat text
<property name="HTTP_PORT" value="8080"></property>

$> sed --regexp-extended 's/(value=\")[0-9]*/\180/' text
<property name="HTTP_PORT" value="80"></property>

Upvotes: 0

Related Questions