![AWK 中的逆正規表示式?](https://rvso.com/image/97228/AWK%20%E4%B8%AD%E7%9A%84%E9%80%86%E6%AD%A3%E8%A6%8F%E8%A1%A8%E7%A4%BA%E5%BC%8F%EF%BC%9F.png)
我正在嘗試過濾掉包含特定單字的行。正規表示式是腳本的命令列輸入。
$0 ~ regex {
//Do something.
}
輸入範例為:
**String** **number**
domain 1
domain 2
bla 3
因此,從上面的輸入中,使用者可以說 - 過濾掉包含單字“domain”的行。
我嘗試過的:
regex = "\?\\!domain"
(負向前瞻)。
但這個正規表示式正在過濾掉每一行。不只是帶有“域”一詞的行。
答案1
input
對於包含以下內容的給定輸入檔:
domain
demesne
過濾包含以下內容的行domain
:
$ awk '/domain/ { print }' input
domain
過濾行不是包含domain
:
$ awk '!/domain/ {print }' input
demesne
用於基於過濾場地我們可以對新的給定檔案嘗試以下操作,而不是整行input
:
example www.example.com
exemplar www.example.net
過濾掉第一個欄位所在的行包含 example
:
$ awk '$1 !~ /example/ { print }' input
exemplar www.example.net
在您的問題中,您使用的$0
是整行而不是第一個欄位。
答案2
另一種更靈活/更強大的過濾行的方法是{next}
:
- 為了列印所有行不要匹配給定的
regex
,執行以下操作:awk '/regex/ {next} {print}' inputfile
您甚至可以使用此方法過濾掉兩個特定行之間的所有行,如下所示:
列印所有行不是在行匹配
regex1
和第一個下一行匹配之間regex2
,執行以下操作:awk '/regex1/,/regex2/ {next} {print}' inputfile
這是不可能的方法
awk '!/regex/'
(如果我沒記錯的話)。
例如,如果您inputfile
的內容是這樣的:
hello, here is my confidential information
SECRET INFO BEGIN
xx
x
xxxxx
xxxx
xxxx
xxxxx
xs
sdf
sdfsdfw
wefwe
SECRET INFO END
This is the end of my message
然後,該命令awk '/SECRET INFO BEGIN/,/SECRET INFO END/ {next} {print}' inputfile
將列印:
hello, here is my confidential information
This is the end of my message
答案3
echo 'hello, here is my confidential information
SECRET INFO BEGIN
xx
x
xxxxx
xxxx
xxxx
xxxxx
xs
sdf
sdfsdfw
wefwe
SECRET INFO END
This is the end of my message' |
mawk 'BEGIN { _^= FS = RS } ! /SECRET INFO/ ? _ : _ * (_=!_)'
gawk 'BEGIN { _^= FS = "SECRET INFO" } _*(NF <= _^_ || _=!_)'
hello, here is my confidential information
This is the end of my message