检查文件中包含特定字母的单词数

afs*_*137 1 shell-script text-processing

Bash命令检查文件中包含字母“a”的单词数

Joh*_*024 14

假设我们有这个测试文件:

$ cat file
the cat in the hat
the quick brown dog
jack splat
Run Code Online (Sandbox Code Playgroud)

通过grep采用 GNU-o扩展的实现,我们可以检索包含a以下内容的所有单词:

$ grep -wo '[[:alnum:]]*a[[:alnum:]]*' file
cat
hat
jack
splat
Run Code Online (Sandbox Code Playgroud)

我们可以数出这些词:

$ grep -wo '[[:alnum:]]*a[[:alnum:]]*' file | wc -l
4
Run Code Online (Sandbox Code Playgroud)


yae*_*shi 8

POSIXly:

<file tr -s '[:space:]' '[\n*]' | grep -c a
Run Code Online (Sandbox Code Playgroud)

在这里,单词是非空格字符的序列。


ter*_*don 5

这是一种 Perl 方式:

 perl -0lnE 'say scalar grep(/a/,split(/\s/,$_));' file
Run Code Online (Sandbox Code Playgroud)

还有一种awk方法:

 awk '{for(i=1;i<=NF;i++){if($(i)~/a/){k++}}}END{print k}' file
Run Code Online (Sandbox Code Playgroud)