Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sed using extended regexp and capture groups

Tags:

regex

sed

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.

like image 564
Chris Seymour Avatar asked Oct 29 '12 20:10

Chris Seymour


People also ask

Can you use regex in sed?

Regular expressions are used by several different Unix commands, including ed, sed, awk, grep, and to a more limited extent, vi.

What is matching group in regex?

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.

What does this regex do?

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.


1 Answers

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
like image 115
ДМИТРИЙ МАЛИКОВ Avatar answered Sep 30 '22 19:09

ДМИТРИЙ МАЛИКОВ