【问题标题】:awk script is not running the middle blockawk 脚本没有运行中间块
【发布时间】:2021-11-29 08:22:50
【问题描述】:

以下脚本将只运行 BEGIN 和 END 块:

#!/bin/awk -f

BEGIN {print "Hello, World!"}
{ print "Don't Panic" }
END { print "and we're panicking... I told you not to panic.  Did you miss that part?" }

输出是:

$ awk -f joint.awk .
  Hello, World!
  and we're panicking... I told you not to panic.  Did you miss that part?

预期的输出是:

$ awk -f joint.awk .
  Hello, World!
  Don't panic
  and we're panicking... I told you not to panic.  Did you miss that part?

奇怪的是,当我将中间块更改为print $1 时,不是打印一段文本,而是在我传入文件时按预期运行。

【问题讨论】:

  • 标准输入上有数据吗?中间块只有在有数据时才会运行。
  • 参见例如ideone.com/tggrLw -- 两行输入,你得到Don't Panic 打印两次。零行输入,它永远不会被打印出来。
  • awk -f joint.awk . 会产生关于. 是目录而不是文件的错误消息(或GNU awk 中的警告)。请务必阅读从运行工具中获得的任何警告或错误消息,并在发布问题时包含任何此类消息。在您使用 -f 传递给 awk 的文件中,任何存在的 shebang 都将被忽略,仅作为注释。如果你想编写一个调用 awk 的 shell 命令,那么 a) 不要用“.awk”扩展名来命名它,b) 不要用其中的 shebang 调用 awk,在 shebang 中使用一个 shell 并调用 awk从中,见stackoverflow.com/a/61002754/1745001

标签: awk


【解决方案1】:

具有明确无条件的内行在标准输入上的每行输入运行一次(或在您的输入文件中,如果明确命名的话)。

因此,Don't Panic 被打印多少次取决于有多少输入。

通过以下代码查看此测试:

awkScript=$(cat <<'EOF'
BEGIN {print "Hello, World!"}
{ print "Don't Panic" }
END { print "and we're panicking... I told you not to panic.  Did you miss that part?" }
EOF
)
 
echo "Testing with no input:"
awk "$awkScript" </dev/null
echo
echo "Testing with one line of input:"
awk "$awkScript" <<<"One line of input"
echo
echo "Testing with two lines of input:"
awk "$awkScript" <<<$'First line\nSecond line'

...作为输出发出:

Testing with no input:
Hello, World!
and we're panicking... I told you not to panic.  Did you miss that part?

Testing with one line of input:
Hello, World!
Don't Panic
and we're panicking... I told you not to panic.  Did you miss that part?

Testing with two lines of input:
Hello, World!
Don't Panic
Don't Panic
and we're panicking... I told you not to panic.  Did you miss that part?

【讨论】:

  • 工作示例就像一张图片——价值 1000 字。我希望他在awkScript 中获得流程替换和heredoc。额外学习的奖励。
  • 谢谢!正如您所指出的,我对 awk 流程的理解是不正确的。这解决了它!
猜你喜欢
  • 2018-08-28
  • 1970-01-01
  • 2010-10-19
  • 1970-01-01
  • 2018-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-11
相关资源
最近更新 更多