I wrote the following sed one liner for substituting the 3rd portion of an IP address.
sed 's/192\.168\.[0-9]*\.\([0-9]*\)/192.168.15.\1/g'
192.168.0.1
192.168.15.1
I want to make it lazy so it would replace 192.168.0
with 192.168.15
by using ??
which is extended regexp but when I supply the '-r' option I get the following error.
$ sed -r 's/192\.168\.[0-9]*\.\([0-9]*\)/192.168.15.\1/g'
sed: -e expression #1, char 44: invalid reference \1 on `s' command's RHS
Can you explain what is going on here and how to make an expression lazy whilst using capture groups?
Note: I can achieve the example using many different approaches, my question isn't how to solve the example. I am interesting in using sed with exteneded regexp and capture groups.
Regular expressions are used by several different Unix commands, including ed, sed, awk, grep, and to a more limited extent, vi.
Regular expressions allow us to not just match text but also to extract information for further processing. This is done by defining groups of characters and capturing them using the special parentheses ( and ) metacharacters. Any subpattern inside a pair of parentheses will be captured as a group.
Short for regular expression, a regex is a string of text that lets you create patterns that help match, locate, and manage text. Perl is a great example of a programming language that utilizes regular expressions. However, its only one of the many places you can find regular expressions.
There is no need to escape braces because ([0-9]*)
is valid statement matching group of symbols.
$> echo "192.168.0.1" | sed -r 's/192\.168\.[0-9]*\.([0-9]*)/192\.168\.15\.\1/g'
192.168.15.1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With