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)
POSIXly:
<file tr -s '[:space:]' '[\n*]' | grep -c a
Run Code Online (Sandbox Code Playgroud)
在这里,单词是非空格字符的序列。
这是一种 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)