[英]Counting grep result wont work in bash script
我的問題不容易提出,我嘗試通過以下示例說明問題:
/home/luther/tipical_surnames.txt
Smith
Johnson
Williams
Jones
Brown
#Davis
Miller
Wilson
#Moore
Taylor
Anderson
/home/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
怎么了?
更新:就像我寫的一樣,我在其他計算機上測試了腳本,一切正常。 我嘗試以下操作后:
root@problematic:/var/www# cat testfile.bash
#!/bin/bash
for (( c=1; c<=5; c++ ))
{
echo $c
}
root@problematic:/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++ ))
root@problematic:/var/www# echo $BASH_VERSION
4.2.37(1)-release
root@problematic:/var/www#
當然,在其他計算機上,此簡單腳本可以按預期工作,沒有錯誤。
顯然,這是未經測試的,因為您還沒有發布示例輸入,但是這是您應該使用的一種方法:
awk '
NR==FNR { if (!/#/) cnt[$1]=0; next }
{ cnt[$WHATEVER]++ }
END {
PROCINFO["sorted_in"] = "@val_num_desc"
for (name in cnt) {
print name, cnt
if (++c == 5) {
break
}
}
}
' /home/luther/tipical_surnames.txt /home/luther/employers.txt
將“ WHATEVER”替換為存儲在ploys.txt中員工姓氏的字段編號。
上面的代碼使用GNU awk進行sorted_in,與其他awks一樣,我只是從輸出循環中刪除PROCINFO行和計數,然后將輸出通過管道傳遞給sort然后例如head:
awk '
NR==FNR { if (!/#/) cnt[$1]=0; next }
{ cnt[$WHATEVER]++ }
END {
for (name in cnt) {
print name, cnt
}
}
' /home/luther/tipical_surnames.txt /home/luther/employers.txt | sort -k2,1nr | head -5
或其他正確的排序選項。
我實際上不太確定。 我通過使用想象的數據( /usr/share/dict/words
)復制並粘貼來測試您的腳本,該腳本似乎可以正常工作。 我想知道您發布的腳本和您正在運行的腳本之間是否有區別?
在此期間,我采取了使它運行更流暢的自由方式。 請注意,在循環中,如何在每次迭代中讀取整個姓氏文件? 同樣, grep
+ wc -l
可以被grep -c
代替。 由於模式( #
)是固定字符串,因此我還在grep
的第一次調用中添加了-F
。 雇員文件中的grep
使用\\<$name\\>
來確保當$name
為John
時,我們僅獲得Johns,而沒有Johnssons。
#!/bin/bash
employees_in="/usr/share/dict/words"
names_in="/usr/share/dict/words"
grep -v -F "#" "$names_in" | head -n 5 | cut -f 1 |
while read -r name; do
count="$( grep -c "\<$names\> " "$employees_in" )"
printf "name: %-10s\tcount: %d\n" "$name" "$count"
done
測試它:
$ bash script.sh
name: A count: 1
name: a count: 1
name: aa count: 1
name: aal count: 1
name: aalii count: 1
注意:由於字典(僅包含唯一詞)(不足為奇),因此我只得到一個。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.