为什么这个awk脚本也要打印原始文件?

时间:2019-03-28 09:00:20

标签: awk

我有以下脚本:

ascript2.awk

#!/usr/bin/awk -f
BEGIN {FS=":"} 
a[$1]=a[$1] ";" $2 " : " $3
END{
for (x in a) print x,a[x]}        

当我让它运行时,它还会打印原始输入文件。为什么? 当我制作这样的bash脚本时,它可以正常工作:

合并

#!/bin/bash
awk -F' *: *' '{a[$1]=a[$1] (a[$1]?" \\ " :" ; ") $2 ":" $3} END {for (x in a) print x,a[x]}' $1

输入:

Affe : 3 : test
Affe : 5 : test2
Money : 9 : test3

输出:

$ ./merge t.txt
Money  ; 9:test3
Affe  ; 3:test \ 5:test2

$ ./ascript2.awk t.txt
Affe : 3 : test
Affe : 5 : test2
Money : 9 : test3
Money  ; 9  :  test3
Affe  ; 3  :  test; 5  :  test2

1 个答案:

答案 0 :(得分:4)

ascript2.awk中,a[$1]=a[$1] ";" $2 " : " $3应该用大括号括起来,否则它将被解释为不执行任何操作的条件,任何不执行操作的条件将仅在以下情况下打印该行:满足条件。(请参阅:what is the meaning of 1 at the end of awk script

因此您的脚本应如下所示:

#!/usr/bin/awk -f
BEGIN { FS=":" } 
{ a[$1] = a[$1] ";" $2 " : " $3 }
END { for (x in a) print x, a[x] }
相关问题