如何在Linux中返回多个文件中的字符串计数
我有多个xml文件,我想计算其中的一些字符串。 在Linux中如何使用文件名返回字符串计数? 我要计算InvoıceNo的字符串: 结果将是如何在Linux中返回多个文件中的字符串计数,linux,string,bash,shell,count,Linux,String,Bash,Shell,Count,我有多个xml文件,我想计算其中的一些字符串。 在Linux中如何使用文件名返回字符串计数? 我要计算InvoıceNo的字符串: 结果将是 test.xml InvoiceCount:2 test1.xml InvoiceCount:5 test2.xml InvoiceCount:10 下面的awk可能也会对您有所帮助,因为您没有显示任何示例输入,所以没有对其进行测试 awk 'FNR==1{if(count){print value,"Invoi
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
GNU awk使用gsub
进行计数:
$ 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
引用自:一个小shell脚本将满足您的需要
#!/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.xmltest.xml`如何对应于
InvoiceCount
as 2?我们映射到哪里?invoicecount以相同的方式写入每个xml。@1010111100011,请务必添加示例输入,以便于我们更清楚地理解代码标记,这将有助于我们更好地理解问题。谢谢大家,继续分享,继续学习,干杯。