簡體   English   中英

Linux->終端命令-> Grep->與符號有關的表達式/異常

[英]Linux -> Terminal command -> Grep -> Expressions / Exceptions related to symbol

簡而言之:我的命令有問題,該命令應該向我顯示包含以下兩個表達式之一的行:“ king”“ king's son” 這是我到目前為止的去處:

grep -w "king's son\|king" frog.txt

它確實有效,但是它包含不應發生的“國王”

添加-v grep "king's"不起作用,因為它也會刪除“ king's son”

我正在使用Virtual Box Machine上安裝的Ubuntu 32位系統。

-w也不會有多大效果,因為king是在考慮一個字king's'是一個非字字符。

采用:

grep -E "([[:space:]]|^)king('s son)?([[:space:]]|$)" frog.txt

或者,如果您的grep具有可用的PCRE選項,則使用環視方法

grep -P "(?<=[[:space:]]|^)king('s son)?(?=[[:space:]]|$)" frog.txt
grep -E "([[:space:]]|^)king('s son)?([[:space:]]|$)" frog.txt

例如,如果frog.txt包含

kingb    # no match
king's   # no match
king-bee # no match 
breaking # no match
king's hello # no match
king's sonth # no match

king     # match
a king bee  # match
king    bee # match (with a TAB)
king's son  # match

然后上面的命令返回

king     # match
a king bee  # match
king    bee # match (with a TAB)
king's son  # match

這應該做到:

grep -E "(^|[ \t])(king|king's son)([ \t]|$)" frog.txt

它使用組(^|[ \\t])([ \\t]|$)來匹配單詞分隔符或行的開頭/結尾。

grep -w "king's son\|king$" frog.txt

以下幾行可能適合您的情況。

grep -w "king's son\|king$\|king\ " frog.txt

結果是:

king's son   #match
king         #match
king's hello #not match

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM