AWK 中的逆正規表示式?

AWK 中的逆正規表示式?

我正在嘗試過濾掉包含特定單字的行。正規表示式是腳本的命令列輸入。

$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

相關內容