awk:如何执行命令并读取其输出 [英] awk: how to execute a command and read its output

查看:578
本文介绍了awk:如何执行命令并读取其输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从stdin读取数据并为每个解析的行执行一个shell命令并恢复其输出.

I would like to read data from stdin and execute a shell command for each parsed line and recover its output.

下面是一个几乎可行的示例:

Here an example which almost works:

[root@eulbi002] # ping eulbi001 | awk -F'[ =]' '/64 bytes/{"date +%s"|getline D; print D,$11}'
1360069298 0.056
1360069298 0.051
1360069298 0.051

执行了"date +%s"命令,我可以恢复输出,但是在我看来,执行只发生一次,而不是每次比赛都发生.

The command 'date +%s' is executed and I can recover the output, but it looks to me like the execution happens only once, not on every match.

最终目的是将输出移交给rrdtool进行存储,而rrdtool希望为每个记录添加一个时间戳.

The ultimate aim is to hand the output over to rrdtool for storage and rrdtool wants a timestamp for each record.

@Ed Morton除了指出了可行的解决方案外,还提到了gawk及其内置的时间功能.这是最优雅的解决方案.

@Ed Morton, in addition to point out a working solution, mentioned gawk with its built-in time functions. This is the most elegant solution.

[root@eulbi002] # ping eulbi001 | awk -F'[ =]' '/64 bytes/{print systime(),$11}'
1360069298 0.056
1360069298 0.051
1360069298 0.051

推荐答案

以防万一,还有另一条关于热线的警告(请参阅 http://awk.info/?tip/getline ),请尝试在每次调用后关闭管道,例如:

Just in case there's yet another getline caveat kicking in here (see http://awk.info/?tip/getline), try closing the pipe after every invocation, e.g.:

ping eulbi001 |
awk -F'[ =]' 'BEGIN{cmd="date +%s"} /64 bytes/{cmd|getline D; close(cmd); print D,$11}'

,看看是否得到不同的结果.但是,您仍然不应该期望D在每一次调用上都会改变,只是每秒改变一次.如果愿意,可以为较小的时间戳添加.%N".

and see if you get different results. You still shouldn't expect D to change on every invocation though, just every second. You could add a ".%N" for smaller granularity of your timestamps if you like.

更好的是,使用带有内置时间函数的GNU awk,因此您根本不需要处理这些东西.

Better yet, use GNU awk with it's builtin time functions so you don't need to deal with this stuff at all.

这篇关于awk:如何执行命令并读取其输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆