格式化awk的输出

时间:2015-02-21 22:23:59

标签: linux bash shell awk

我正在编写awk脚本以确定单词的数量。

awk '$1 ~/the/ {++c}END{print c}' FS=: br.txt
awk '$1 ~/not/ {++c}END{print c}' FS=: br.txt
awk '$1 ~/that/ {++c}END{print c}' FS=: br.txt

并格式化输出,因此标题将是"不是"并且它们下面的行必须是每个单词的数字。我用这个:

awk 'BEGIN { print "the not that"
{ printf "%-10s %s\n", $1, $1 }}' br.txt

问题是我无法在单词下连续获得单词数。我应该更改或添加什么? 谢谢你的努力

2 个答案:

答案 0 :(得分:2)

这是awk应该做你需要的。

awk '$1~/the/ {the++} $1~/not/ {not++} $1~/that/ {that++} END {print "the","not","that\n"the,not,that}' FS=: OFS="\t" br.txt

以下是它的工作原理:

awk '
    $1~/the/ {the++}                        # If field `1` contains  `the` and `1` to variable `the`
    $1~/not/ {not++}                        # If field `1` contains  `not` and `1` to variable `not`
    $1~/that/ {that++}                      # If field `1` contains  `that` and `1` to variable `that`
END {                                       # When all file is read, do
    print "the","not","that\n"the,not,that} # Print header, and the value of variable  `the,not,that`
' FS=: OFS="\t" br.txt                      # Input field separator = `:`. Output separator = `<tab>`. Read file

答案 1 :(得分:1)

为一个awk程序中的所有单词的计数创建单独的变量,即

   awk -F: '$1~/the/{t++} 
        $1~/not/{n++}
        $1~/that/{h++}
       END {
          printf("the\tnot\tthat\n%d\t%d\t%d\n", t,n,h)
       }' br.txt

使用

进行测试
echo "see the fox
the fox is not here
what is not that" \
|  awk -F: '$1~/the/{t++}
   $1~/not/{n++}
   $1~/that/{h++}
  END {
     printf("the\tnot\that\n%d\t%d\t%d\n", t,n,h)
  }'

the     not     hat
2      2       1