Sed regex replace with quotes

Suppose I have a text file with many lines, one of which is:

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

      

And I want to change it using sed:

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

      

How would I do it? I have tried several things, including:

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. Entry and exit are always the same.

+3


source to share


4 answers


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 avoid the "+" plus sign to achieve "1 or more".

Edited original answer (which shows an alternative solution to the problem) *, so given the context you are using, what's 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 to bind search targets using "^" and "$". I've seen cases (similar to what you are doing) where NOT with bindings increases execution time significantly.

Hope this helps.

+1


source


How about directly translating what you want:

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

      



It's not a "smart" solution like you or I might find, but it's as simple as they are, and when you're looking for a static string, that's all you need.

+2


source


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

      

0


source


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

      

0


source







All Articles