linux - 计算字符出现的次数

标签 linux shell command-line

我有一个 .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/

相关文章:

linux - Linux 的最大管道命令

linux - ssh 连接到另一台服务器上的用户并以该用户身份执行 shell 命令

python - 如何通过 SSH 访问多台 PC,并在每台电脑上独立运行一个代码库

security - 这是批处理文件注入(inject)吗?

node.js - Gulp安装: 'fs: re-evaluating native module sources is not supported' and node-sass errors

linux - Sed 在行首添加正斜杠

linux - 做一组后getsockopt SO_RECVBUF 在linux 中显示两倍的值?

linux - 为什么打开新终端时不执行.bashrc?

shell - 复制/粘贴到 emacs ansi-term shell 中

windows - 如何从批处理文件运行 PowerShell 脚本