awk脚本;打印不输出我想要的地方

时间:2014-03-27 20:23:04

标签: bash awk

我有一个使用AWK脚本的作业,我很难理解为什么我遇到这个问题。基本上我只是想在我的脚本末尾输出一行简单的输出,但由于某种原因它不起作用。

print "Listed are their names (sorted by last names) and phone numbers:"
for(i = 1; i < x; i++)\
       {print "    "topNames[i]"--"topPhones[i] | "sort -k 2";}
print "        Thanks to all of you for your continued support!!"

正在输出:

Listed are their names (sorted by last names) and phone numbers:
        Thanks to all of you for your continued support!!
    John Goldenrod--(916) 348-4278
    Mike Harrington--(510) 548-1278
    Archie McNichol--(206) 548-1348
    Guy Quigley--(916) 343-6410
    Dan Savage--(406) 298-7744
    Tom Savage--(408) 926-3456
    Elizabeth Stachelin--(916) 440-1763

虽然我希望如此:

Listed are their names (sorted by last names) and phone numbers:
    John Goldenrod--(916) 348-4278
    Mike Harrington--(510) 548-1278
    Archie McNichol--(206) 548-1348
    Guy Quigley--(916) 343-6410
    Dan Savage--(406) 298-7744
    Tom Savage--(408) 926-3456
    Elizabeth Stachelin--(916) 440-1763
       Thanks to all of you for your continued support!!

我真的很困惑,为什么它没有按照我希望的顺序输出。

另请注意。什么是AWK脚本的良好编程风格(注释等)?我习惯使用C ++,所以我不确定在哪里放置缩进以及如何对齐我的评论。

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:2)

您可能需要close()排序:

print "Listed are their names (sorted by last names) and phone numbers:"
sortcmd = "sort -k 2"
for (i = 1; i < x; i++) {
    printf "    %s--%s\n", topNames[i], topPhones[i] | sortcmd
}
close(sortcmd)
print "Thanks to all of you for your continued support!!"

http://www.gnu.org/software/gawk/manual/html_node/Redirection.html#Redirection

答案 1 :(得分:0)

将最终的print语句放在END

END   { print "        Thanks to all of you for your continued support!!"}

来自doc

  

在读取所有输入后,END规则仅执行一次