I wrote this in a comment because I didn't realize that this is already the solution. The OP wrote it works, so this time as an answer:
sed "s/\(name=\"port\" *value=\"\)[0-9]*/\1$NEWPORT/g" config.xml
The regular expression suggested by the OP used a couple of non-standard extensions, so it didn't work with sed
, but you don't need them:
I use sed -i to replace the port value in a xml file,
But I don't know how escape the regex, my regex is below.
- instead of the "lookbehind"
(?<=somestring)
you can use the string as is, but it in \(somestring\)
to mark it as subexpression and reuse it in the replacement as \1
, thus instead of saying "this needs to be there, but not get replaced", just replace it with itself
- The
+
is a shortcut for \{1,\}
(one or more occurences), but you can also replace a+
with aa*
. In this case it's probably save to use a simple *
, because zero occurences are impossible
- The
\d
is not better to read than [0-9]
, in my opinion
\s
can be replaced by [[:space:]]
or [ <literal tab>]
. Here a simple whitespace does the job
Conclusion: Almost all reg-ex extensions can easily be avoided, maybe giving a little lengthy pattern or harder to read, but often without disadvantage. An exception is the non-greedy match: In some cases you need a different concept without them.
sed
because it doesn't support lookarounds and\d
will matchd
instead of numbers.. see https://unix.stackexchange.com/questions/119905/why-does-my-regular-expression-work-in-x-but-not-in-y for details – Sundeep Oct 08 '19 at 08:59"s/\(name=\"port\" *value=\"\)[0-9]*/\1$NEWPORT/g"
? – Philippos Oct 08 '19 at 14:15