我有一个 .txt 文件
ID Number Name Fed Sex Tit Wtit
4564 A B M Yusop, Tapan BAN M
59841212 A Rafiq IND F WFM WFM
19892 Aadel F , Arvin IND M
.
.
.
我必须在linux命令行中计算这个文件中有多少个女性F和男性M。
我是 Linux shell 新手,所以我只考虑 grep
命令,但“名称”中也可以有“M”和“F”。
有什么建议吗?
最佳答案
我将使用 awk 来执行此操作(既查找列,又进行计数):
$ awk '
# first line
NR == 1 {
if (col = index($0, "Sex")) {
next # skip rest of script for this line
}
print "Could not find the required header"
exit
}
# all lines
{
# increment counts of each `M` or `F`
++count[substr($0, col, 1)]
}
END {
# loop through count array and print
for (i in count) print i, count[i]
}' file
关于linux - 计算字符出现的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48789387/