2016-08-19 40 views
0

我讀過sed信息。在「3.3正則表達式語法概述」中。
有一個說明:如何使用數字在sed正則表達式

\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. 

我不知道這意味着什麼。誰能給我一個例子?

+0

另請參閱:[Capture Groups](http://stackoverflow.com/documentation/regex/660/capture-groups#t=201608190817276898192) – Sundeep

回答

2

當然!

$ echo "23 45" | sed -r 's/^([0-9]*)/---\1---/' 
---23--- 45 

圖形:

sed -r 's/^([0-9]*)/---\1---/' 
#   ^^^^^^^^ ^^ 
#   capture -----| 
#     print back 

正如你看到的,形式s/search/replace上一個sed表達式,可以「捕捉」在搜索塊的模式,然後打印它放回使用\1,\2,...替換塊。編號是順序的,對應於已捕獲的第1,第2,...組。

$ echo "23 45" | sed -r 's/^([0-9]*) (.)/YEAH \2---\1---/' 
YEAH 4---23---5