Reputation: 359
I've read sed info. In "3.3 Overview of Regular Expression Syntax".
There is a description:
\digit
Matches the digit-th \(...\) parenthesized subexpression in the regular expression.
This is called a back reference. Subexpressions are implicitly numbered by
counting occurrences of \( left-to-right.
I don't know what it means. Who can give me a example?
Upvotes: 2
Views: 1880
Reputation: 289495
Sure!
$ echo "23 45" | sed -r 's/^([0-9]*)/---\1---/'
---23--- 45
Graphically:
sed -r 's/^([0-9]*)/---\1---/'
# ^^^^^^^^ ^^
# capture -----|
# print back
As you see, in a sed expression on the form s/search/replace
, you can "capture" a pattern in the search block and then print it back in the replace block by using \1
, \2
, ... The number is sequential and corresponds to the 1st, 2nd, ... group that has been captured.
$ echo "23 45" | sed -r 's/^([0-9]*) (.)/YEAH \2---\1---/'
YEAH 4---23---5
Upvotes: 5