我有一個輸出文件,這看起來是這樣的:grep的-c無法識別參數
[email protected]
[email protected]
[email protected]
我想找出與grep
,該value2
出現了多少次,所以我「M這樣做:
n = grep -c 'value2' outputfile.tmp
if[$n!=6] ; then
但是當我運行它,控制檯這樣說:
`"-c: command not found"`
就像它不識別參數。
我有一個輸出文件,這看起來是這樣的:grep的-c無法識別參數
[email protected]
[email protected]
[email protected]
我想找出與grep
,該value2
出現了多少次,所以我「M這樣做:
n = grep -c 'value2' outputfile.tmp
if[$n!=6] ; then
但是當我運行它,控制檯這樣說:
`"-c: command not found"`
就像它不識別參數。
您需要使用$()來包圍命令將其設置爲一個變量:
n=$(grep -c 'value2' outputfile.tmp)
這是一種命令替換的,看到附近的這個頁面的底部:http://www.tldp.org/LDP/abs/html/commandsub.html
這應該已經用空格阻止了賦值n =
:Bash參數賦值不能有空格。其次,將一個命令的輸出分配給一個參數,你必須使用command substitution:
n=$(grep -c 'value2' outputfile.tmp)
注意,這會告訴你有多少線包含至少出現一次的value2
,而不是實際數量爲value2
。試想一下:
$ grep -c 'value2' <<< 'value2value2'
1
如果你知道,只會有一個value2
每行(或要計算行),我們是很好的。如果你要計算的出現,你必須使用類似
n=$(grep -o 'value2' outputfile.tmp | wc -l)
grep -o
打印在單獨的行每場比賽,並wc -l
計數線。
現在,要檢查$n
的值是否不等於六,請使用條件。與作業不同,此必須有有空格。
!=
比較用於字符串比較;爲整數,你應該使用-ne
( 「不等於」):
if [ "$n" -ne 6 ]; then
取而代之的是測試命令[ ]
的,Bash有更靈活的[[ ]]
條件epxression:
if [[ "$n" -ne 6 ]]; then
其中引用不嚴格必要(但不傷害!)。
或者,我們可以使用一個算術表達式:
if ((n != 6)); then
其中任何參數而沒有預先考慮$
評價。