![](/img/trans.png)
[英]How to print using awk in UNIX the text from many files in different ways (by the file name position in argc)?
[英]How to print total count of multiples strings from a text file using awk
我是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
您缺少“ for”循环的花括号-您应该具有:
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
假设您的输入是各个单词之间用空格隔开的行,请按以下步骤操作:
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
如果那不是您输入的内容,请更新您的问题以显示它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.