[英]How to return string count in multiple files in Linux
我有多個xml文件,我想在其中計算一些字符串。 如何在Linux中使用文件名返回字符串計數? 我要計算InvoıceNo的字符串:結果將為;
test.xml InvoiceCount:2
test1.xml InvoiceCount:5
test2.xml InvoiceCount:10
跟隨awk可能會對您有所幫助,因為您沒有顯示任何示例輸入,因此請不要對其進行測試。
awk 'FNR==1{if(count){print value,"InvoiceCount:",count;count=""};value=FILENAME;close(value)} /InvoiceCount/{count++}' *.xml
使用grep -c
獲取匹配行數
for file in *.xml ; do
count=$(grep -c $PATTERN $file)
if [ $count -gt 0 ]; then
echo "$file $PATTERN: $count"
fi
done
首先測試文件:
$ cat foo.xml
InvoiceCount InvoiceCount
InvoiceCount
$ cat bar.xml
InvoiceCount
使用gsub
進行計數的GNU awk:
$ awk '{
c+=gsub(/InvoiceCount/,"InvoiceCount")
}
ENDFILE {
print FILENAME, "InvoiceCount: " c
c=0
}' foo.xml bar.xml
foo.xml InvoiceCount: 3
bar.xml InvoiceCount: 1
您可能可以使用以下代碼
PATTERN=InvoiceNo
for file in *.xml
do
count=$(grep -o $PATTERN "$file" | wc -l)
echo "$file" InvoiceCount:$count
done
產量
test.xml InvoiceCount:1
test1.xml InvoiceCount:2
test2.xml InvoiceCount:3
引用自: https ://unix.stackexchange.com/questions/6979/count-total-number-of-occurrences-using-grep
一個小殼skript會想要你想要的
#!/bin/bash
for file in *
do
awk '{count+=gsub(" InvoıceNo","")}
END {print FILENAME, "InvoiceCount:" count}' $file
done
將代碼放在文件(例如counter.sh)中,然后像這樣運行:
counter.sh text.xml text1.xml text2.xml
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.