我的問題是不容易問,我試着用下面的例子說明問題:計數grep的結果在bash腳本不會工作
/home/luther/tipical_surnames.txt
Smith
Johnson
Williams
Jones
Brown
#Davis
Miller
Wilson
#Moore
Taylor
Anderson
/家/luther/employers.txt
2000 Johnson A lot-of details/BJC3000,6000, i550 0
2101 Smith A lot-of details/BJC3000,6000, i550 0
2102 Smith A lot-of details/BJC3000,6000, i550 0
2103 Jones A lot-of details/BJC3000,6000, i550 0
2104 Johnson A lot-of details/BJC3000,6000, i550 0
2100 Smith A lot-of details/BJC3000,6000, i550 0
我有一個最喜歡的姓氏列表和另一個僱主的名字。 讓我們來看看有多少人在該公司擁有最流行的姓,使用控制檯:
grep -v "#" /home/luther/tipical_surnames.txt | sed -n 1'p' | cut -f 1
Smith
grep Smith /home/luther/employers.txt | wc -l
230
工作完美。 現在讓我們用一個簡單的bash腳本檢查前5個最受歡迎的姓氏:
#!/bin/bash
counter=1
while [ $counter -le 5 ]
do
surname=`grep -v "#" /home/luther/tipical_surnames.txt | sed -n "$counter"'p' | cut -f 1`
qty=`grep "$surname" /home/luther/employers.txt | wc -l`
echo $surname
echo $qty
counter=$(($counter + 1))
done
而且結果如下:
Smith
0
Johnson
0
Williams
0
Jones
0
Brown
0
的哪些錯誤?
更新: 就像我寫的,我測試了其他電腦上的腳本,一切工作正常。 後,我嘗試如下:
[email protected]:/var/www# cat testfile.bash
#!/bin/bash
for ((c=1; c<=5; c++))
{
echo $c
}
[email protected]:/var/www# bash testfile.bash
testfile.bash: line 2: syntax error near unexpected token `$'\r''
'estfile.bash: line 2: `for ((c=1; c<=5; c++))
[email protected]:/var/www# echo $BASH_VERSION
4.2.37(1)-release
[email protected]:/var/www#
當然,其他計算機上如預期這只是劇本的工作,沒有錯誤。
shell是調用工具的環境,而不是操縱文本的工具。用於處理文本的標準通用UNIX工具是awk。由於您使用了錯誤的工具,因此您正在努力工作,並且在shell中執行您想要的功能會非常複雜且效率低下(請參閱[爲什麼要使用shell循環處理文本]認爲壞實踐(http://unix.stackexchange.com/questions/169716/why-is-using-a-shell-loop-to-process-text-considered-bad-practice))。把它扔掉,用awk重新開始。發佈簡潔,可測試的樣本輸入和預期輸出,我們可以爲您提供幫助。 –
我猜你是有DOS行結束符的文件。複製/粘貼程序輸出時,你不會看到它們,但它們會出現在捕獲的變量中,並阻止最終的'grep'匹配任何東西。在文件上嘗試'dos2unix'。爲了進一步排除故障,[Stack Overflow'bash' tag wiki](// stackoverflow.com/tags/bash/info)有關於這個問題的詳細部分。 – tripleee
@Ed Morton好吧,它很清楚,但我仍然不明白爲什麼我的代碼會很好,如果我將$ surname變量替換爲值。正如你從結果中看到的,當我想把它打印到屏幕上時,$ surname變量具有很好的價值。爲什麼當我使用聲明$ qty變量時,同一個變量不會工作? – Luther