2013-02-05 67 views
2

我通過一些文件查找字符串'host'(帶有單引號)。我想捕獲沒有評論(#)的字符串文件。與Grep不一致的結果

第一個例子中的測試用例工作得很好,但下面的第二種情況沒有。第二種情況是我創建的測試文件,並在其中插入了前導空格。所以我知道沒有控制字符,只有空格。

這兩個服務器都是相當新的Linux版本。

什麼可以解釋第二個例子不捕獲文本?我知道我只能grep爲主機,然後用篩選grep -v的評論,但它讓我感到不知所措。

/home/user2> $ cat set.txt 
    'host' 
/home/user2> $ grep -E "^\s+'host'" set.txt 
    'host' 

grep的其他Linux服務器上不捕獲所需的數據:

[[email protected] ~]$ cat set.txt 
    'host' 
[[email protected] ~]$ grep -E "^\s+'host'" set.txt 
[[email protected] ~]$ 
+0

也許這些命令在不同的grep風格上是別名?你可以檢查嗎? –

+0

好問題。我跑了「set」和「env」,沒有任何別名。 – EdgeCase

+0

'grep -V'報告grep命令的同一版本? –

回答

0

根據grep版本和類型,\s可能無法正常工作。在我的系統上使用grep 2.12,沒有提及\s,儘管它仍然可以工作。其他版本可能沒有啓用此功能。

從手冊頁:

The Backslash Character and Special Expressions 
    The symbols \< and \> respectively match the empty string at the 
    beginning and end of a word. The symbol \b matches the empty string at 
    the edge of a word, and \B matches the empty string provided it's not 
    at the edge of a word. The symbol \w is a synonym for [_[:alnum:]] and 
    \W is a synonym for [^_[:alnum:]]. 

此外,man grep | grep "\\\\s"回報什麼都沒有。就是這樣:沒有提及\s

相反,你可以使用[:space:]像這樣:

[email protected] $ grep -E "^[[:space:]]+'host'" set.txt 
    'host' 

所以檢查你的grep版本,並且去,在所有這些工作的語法。 This mailing list post表示\s在grep 2.5.1中不起作用,但是在2.6.3中工作,所以你有一個2.6.3之前的版本,它可能不適用於\s