我对awk非常陌生,所以我对这个问题有点麻烦。我需要做的是编写一个脚本,打印三个字符串“他们”,“他”“她”的计数,但我只能在awk中执行此操作,并且单词区分大小写。到目前为止,它只打印文本文件(这是一篇文章)中出现的“他们”的次数,而不是其他的。关于如何仅在awk中执行此操作的一些输入将是很好的。这是我到目前为止所拥有的
awk 'BEGIN {print "They" " " "He" " " "She"} #printing header
{for (i=0;i<=NF;i++)if ( $i =="They" ) numA++;
if ( $i =="He" ) numB++;
if ( $i =="She" ) numC++ } END {print numA," ", numB, " ", numC}' myFile.txt
预期输出应为:
They He She
24 16 17
答案 0 :(得分:2)
你错过了&#39; for&#39;循环 - 你应该:
awk 'BEGIN {print "They" " " "He" " " "She"} #printing header
{for (i=0;i<=NF;i++)
{
if ( $i =="They" ) numA++;
if ( $i =="He" ) numB++;
if ( $i =="She" ) numC++;
}
} END {print numA," ", numB, " ", numC}' myFile.txt
答案 1 :(得分:2)
假设您的输入是单独单词的空格分隔行,请按照以下步骤操作:
awk '
BEGIN{
numWords = split("They He She",tmp)
for (i in tmp) {
words[i]
}
}
{
for (i=1;i<=NF;i++) {
if ($i in words) {
cnt[$i]++
}
}
}
END {
for (wordNr=1; wordNr <= numWords; wordNr++) {
printf "%s%s", tmp[wordNr], (wordNr<numWords?OFS:ORS)
}
for (wordNr=1; wordNr <= numWords; wordNr++) {
printf "%d%s", cnt[tmp[wordNr]], (wordNr<numWords?OFS:ORS)
}
}' file
如果这不是您输入的内容,请更新您的问题以显示它。