2010-09-21 250 views
58
% cat temp 
$$$ hello1 
$$ hello2 
    hello3 
## hello4 
    hello5 $$$ 
% cat temp | grep "$$$" 
Illegal variable name. 
% cat temp | grep "\$\$\$" 
Variable name must contain alphanumeric characters. 
% 

我希望到grep爲$$$,我希望得到的結果是

% cat temp | grep <what should go here?> 
$$$ hello1 
    hello5 $$$ 
% 

爲了區別,我也標誌着提示符%

  • 這裏有什麼問題?
  • grep string應該是什麼?
+2

你的第二個命令是正確的(帶有$ escaped),但是你需要使用單引號,而不是雙引號。 – 2010-09-21 11:48:51

回答

77

問題是shell在雙引號字符串內展開變量名。因此,對於"$$$",它會嘗試從第一個$開始讀取變量名稱。

另一方面,在單引號中,變量不會被展開。因此,'$$$'工作 - 如果它不是因爲$是表示行結尾的正則表達式中的特殊字符。所以需要轉義:'\$\$\$'

0

如何^.*[$]{3}.*$

+1

爲什麼^。*和。* $?他們似乎完全沒用... – 2010-09-21 11:48:05

20

當您使用雙引號"或沒有使用雙\: "\\\$\\\$\\\$"

cat t | grep \\\$\\\$\\\$ 

,如果你在單引號用'你可以使用:

cat t | grep '\$\$\$' 
7
$ grep '\$\$\$' temp 
$$$ hello1 
hello5 $$$ 

有你的命令superflous '貓'。