關於awk的范圍模式功能問題
man awk中這樣寫到
The pattern1, pattern2 form of an expression is called a range pattern. It matches all input records starting with a record that matches pattern1, and continuing until a record that matches pattern2, inclusive. It does not combine with any other sort of pattern expression.
表達式的pattern1,pattern2形式稱為范圍模式。 它匹配所有輸入記錄,從與pattern1匹配的記錄開始,並持續到與pattern2匹配的記錄(包括)。 它不與任何其他類型的模式表達式組合。
[root@localhost ~]# awk '/aaa/,/bbb/{print}' file
aaa
grge
ddd
bbb
aaa gege
ccc
bbb
aaa gregeg
eee
bbb
這里的/bbb/並沒有起作用,執行了從/aaa/一直匹配到最后一行
[root@localhost ~]# awk '/aaa/,/ccc/{print}' file
aaa
grge
ddd
bbb
aaa gege
ccc
aaa gregeg
eee
bbb
這里/ccc/並沒有起作用,跟/bbb/一樣,","起作用了,但/bbb/沒有匹配到結果
按照awk的man文檔說明,awk '/aaa/,/bbb/' file結果應該是
aaa
grge
ddd
bbb
可是這里的結果卻是到最后一行,是不是/bbb/這個pattern並沒有匹配到
[root@localhost ~]# seq 9 | awk /3/,/7/
3
4
5
6
7
當每行內容不同,awk的范圍模式能正確執行
[root@localhost ~]# seq 10 | awk /1/,/7/
1
2
3
4
5
6
7
10
當有重復行時,范圍模式會將重復結果顯示
以上是我遇到的一些疑惑,詢問了大神,得到下面的解釋
# awk '/aaa/,/bbb/{print}' file
aaa
grge
ddd
bbb
aaa gege
ccc
bbb
aaa gregeg
eee
bbb
[root@localhost ~]# awk '/aaa/,/ccc/{print}' file
aaa
grge
ddd
bbb
aaa gege
ccc
aaa gregeg
eee
bbb
$ seq 20 | awk '/3/,/7/{print}'
3
4
5
6
7
13
14
15
16
17
$ seq 15 | awk '/3/,/7/{print}'
3
4
5
6
7
13
14
15
$ seq 15 | awk '/1/,/2/{print}'
1
2
10
11
12
13
14
15
$ seq 23 | awk '/1/,/2/{print}'
1
2
10
11
12
13
14
15
16
17
18
19
20
21
這里的最后一行匹配結果有點意外,在同一行里,有1,也有2,並且2在前面,但還是匹配到了;猜測awk在同一行使用范圍匹配時不分順序
總結一下,awk的范圍模式其實很好用的,但有多行內容重復時,結果就要注意了,awk將進行全文匹配
還有就是awk的范圍模式其實sed也有,但這兩者有區別,awk的范圍匹配能將同一行結果匹配,但sed不能匹配同一行的內容