2015-05-30 19 views
2

只需例外:我有命令的問題,應打印我的包含其中任何兩個表達式的臺詞:「王」「國王的兒子」 。這是我到目前爲止:的Linux - >終端命令 - > grep的 - >表達式/相關符號

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

它的工作,但它包括「國王的」不應發生。

添加-v grep "king's"因爲它刪除「國王的兒子」也不起作用。

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

+1

由於您無法從其他用戶獲得正確答案,請考慮留下「frog.txt」的內容。 – goncalotomas

+0

我得到了一個答案,這是我的問題的解決方案:http://stackoverflow.com/a/30550218/4956820 – Advent

+1

我很抱歉,我忽略了它,也許是因爲它沒有upvoted,也沒有被接受。如果這個答案實際上是解決你的問題的方法,那麼你至少應該接受它。這些瓦爾和未來的讀者肯定會很感激它。 :) – goncalotomas

回答

1

這現在應該做的:

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

它使用羣體(^|[ \t])([ \t]|$)匹配單詞分隔或線的開始/結束。

+0

它的工作原理,感謝您的回覆。它沒有失敗,避免添加像「國王的城堡」和東西的東西。再一次感謝你。請加上這個答案,以便與我處於相同情境的人能找到解決方案。 – Advent

1
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 
+0

他們都只有「國王的兒子」返回行。 – Advent

+0

'\ s'不是大多數'grep'方言中空格的有效元表達式。嘗試用'[[:space:]]'替換它。 – tripleee

+0

@tripleee:感謝您的糾正。 – unutbu

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

它只顯示包含「王的兒子」的行,這不是我想要得到的結果。感謝您的迴應。 – Advent

3

因爲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 
+0

他們都沒有工作,第二個是給我線「破」以及。 – Advent

+0

這兩個命令都在工作。如果在'king'之後有製表符的可能性,那麼使用:'grep -E'king('s son)?([[:space:]] | $)「frog.txt」 – anubhava

0

以下行,也許你的情況下工作。

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

結果是:

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

它不起作用對我來說。感謝您的迴應。 – Advent

+1

@Advent:請告訴我們*它如何不起作用。給出一個失敗的例子。那麼也許我們可以改進答案。 – unutbu

+0

你能舉一些例子嗎? – Qian

相關問題