【问题标题】:Awk scripting; print not outputting where I would likeawk 脚本;打印不输出我想要的地方
【发布时间】:2014-03-27 20:23:03
【问题描述】:

我有一个使用 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 脚本的好的编程风格(cmets 等)?我习惯使用 C++,所以我不确定在哪里放置缩进以及如何对齐我的 cmets。

任何帮助将不胜感激。

【问题讨论】:

    标签: bash awk


    【解决方案1】:

    你可能需要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

    【讨论】:

    • 谢谢!那行得通。有什么方法可以在不创建 sortcmd 并只使用常规排序的情况下做到这一点?
    • 你可以print ... | "sort -k 2" 然后close("sort -k 2")。使用变量只是有助于避免命令名称不匹配的错误(手册很清楚它们必须完全匹配)
    • 注意:如果 Tom 的区号小于 Dan 的区号,“Dan Savage”将排在“Tom Savage”之后。试试printf "%s -- %s\n", name, phone | "sort -k 2,2 -k 1,1"
    • +1 到 Q 和 A。很高兴知道不使用 close(..) 的副作用。
    【解决方案2】:

    将最后的打印语句放入END

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

    来自doc

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

    【讨论】:

    • 我忘了提到我的脚本的整个部分都在'END'中
    • @JSarwer:你可以有多个ENDs。尝试把它放在一个单独的(也看看@glenn jackman's answer)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-11
    • 1970-01-01
    • 2017-12-05
    相关资源
    最近更新 更多