如何重定向管道awk脚本



我从awk脚本重定向stdout时遇到问题。

此脚本运行良好:

ping dns.google | awk '{print(substr($7,5));}'

并且输出一次打印行。

现在,我想通过重定向将输出重定向到文件中:

ping dns.google | awk '{print(substr($7,5));}' >> latency.log

这是行不通的,latency.log是空的。

我试图变得聪明,并在awk脚本中重定向输出,如下所示:

ping dns.google | awk '{print(substr($7,5) >> "latency.log");}'

同样latency.log是空的。

awk版本是:

$ awk -V
GNU Awk 4.1.4, API: 1.1 (GNU MPFR 4.0.1, GNU MP 6.1.2)
Copyright (C) 1989, 1991-2016 Free Software Foundation.

我的Linux版本:

$ cat /etc/*release
DISTRIB_ID=LinuxMint
DISTRIB_RELEASE=19.3
DISTRIB_CODENAME=tricia
DISTRIB_DESCRIPTION="Linux Mint 19.3 Tricia"
NAME="Linux Mint"
VERSION="19.3 (Tricia)"
ID=linuxmint
ID_LIKE=ubuntu
PRETTY_NAME="Linux Mint 19.3"
VERSION_ID="19.3"
HOME_URL="https://www.linuxmint.com/"
SUPPORT_URL="https://forums.ubuntu.com/"
BUG_REPORT_URL="http://linuxmint-troubleshooting-guide.readthedocs.io/en/latest/"
PRIVACY_POLICY_URL="https://www.linuxmint.com/"
VERSION_CODENAME=tricia
UBUNTU_CODENAME=bionic

如何将awk输出重定向到文件中?

具有重定向的流程管道是非交互式的(即不与终端关联(,因此awk的 STDOUT 被缓冲并且不会传递到您的文件,直到管道的缓冲区累积到足以被刷新。

规避此问题的一种方法是使用unbuffer.若要在管道中使用它,请添加-p标志:

ping dns.google | unbuffer -p awk '{print(substr($7,5));}' >> latency.log

通常,您会在expect包中找到unbuffer命令。

另一种选择是使用stdbuf

ping dns.google | stdbuf -oL awk '{print(substr($7,5));}' >> latency.log

最新更新