只需例外:我有命令的問題,應打印我的包含其中任何兩個表達式的臺詞:「王」,「國王的兒子」 。這是我到目前爲止:的Linux - >終端命令 - > grep的 - >表達式/相關符號
grep -w "king's son\|king" frog.txt
它的工作,但它包括「國王的」這不應發生。
添加-v grep "king's"
因爲它刪除「國王的兒子」也不起作用。
我正在使用安裝在Virtual Box Machine上的Ubuntu 32位系統。
只需例外:我有命令的問題,應打印我的包含其中任何兩個表達式的臺詞:「王」,「國王的兒子」 。這是我到目前爲止:的Linux - >終端命令 - > grep的 - >表達式/相關符號
grep -w "king's son\|king" frog.txt
它的工作,但它包括「國王的」這不應發生。
添加-v grep "king's"
因爲它刪除「國王的兒子」也不起作用。
我正在使用安裝在Virtual Box Machine上的Ubuntu 32位系統。
這現在應該做的:
grep -E "(^|[ \t])(king|king's son)([ \t]|$)" frog.txt
它使用羣體(^|[ \t])
和([ \t]|$)
匹配單詞分隔或線的開始/結束。
它的工作原理,感謝您的回覆。它沒有失敗,避免添加像「國王的城堡」和東西的東西。再一次感謝你。請加上這個答案,以便與我處於相同情境的人能找到解決方案。 – Advent
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
因爲king
被認爲是一個字king's
作爲-w
幫助不大'
是一個非單詞字符。
用途:
grep -E "([[:space:]]|^)king('s son)?([[:space:]]|$)" frog.txt
或者使用lookarounds如果您grep
有可用PCRE選項:
grep -P "(?<=[[:space:]]|^)king('s son)?(?=[[:space:]]|$)" frog.txt
由於您無法從其他用戶獲得正確答案,請考慮留下「frog.txt」的內容。 – goncalotomas
我得到了一個答案,這是我的問題的解決方案:http://stackoverflow.com/a/30550218/4956820 – Advent
我很抱歉,我忽略了它,也許是因爲它沒有upvoted,也沒有被接受。如果這個答案實際上是解決你的問題的方法,那麼你至少應該接受它。這些瓦爾和未來的讀者肯定會很感激它。 :) – goncalotomas