bash - 如何重定向管道awk脚本
问题描述
我stdout
从awk
脚本重定向时遇到问题。
该脚本运行良好:
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
s STDOUT 被缓冲并且不会传递到您的文件,直到管道的缓冲区积累到足以被刷新。
避免这种情况的一种方法是使用unbuffer
. 要在管道中使用它,请添加-p
标志:
ping dns.google | unbuffer -p awk '{print(substr($7,5));}' >> latency.log
通常,您会在包中找到该unbuffer
命令。expect
另一种选择是使用stdbuf
:
ping dns.google | stdbuf -oL awk '{print(substr($7,5));}' >> latency.log