从system()输出到它之后,AWK变量保留其值

时间:2015-06-29 08:02:26

标签: awk pipe

我想从以下输出中打印包含IP地址(可能不存在)的行:ifconfig $1

如果命令没有返回任何内容,则不应打印任何内容(output应为空)。

这是我正在使用的命令:

echo -e "wlan2 \n eth3" | awk '{
                          command = "ifconfig " $1 " | grep \"inet addr\" ";

                          command | getline output;
                          print $1 output;
                               }'

输出:

wlan2          inet addr:192.168.0.104  Bcast:192.168.0.255  Mask:255.255.255.0
eth3          inet addr:192.168.0.104  Bcast:192.168.0.255  Mask:255.255.255.0

在这种情况下,wlan2有一个IP,eth3 有IP。但是为eth3打印了同一行。

问题:如何确定命令的输出是否为空?或者确保变量output在后​​续迭代中不保留其先前的值?

1 个答案:

答案 0 :(得分:3)

假设你确实有正确的理由在awk中执行此操作(目前,看起来你可以使用shell执行此操作),您需要进行一些更改:

awk '{ command = "ifconfig " $1 " | grep \"inet addr\" " }
     command | getline output > 0  { print $1, output }
     { close(command) }'

通过检查getline的返回值,我们只能在成功时打印该行。使用close也很重要,这样管道就不会打开,因为这会导致更大的输入或重复的线路出现问题。

似乎在awk中grep的管道是一种反模式,所以你最好在awk中进行模式匹配:

awk '{ command = "ifconfig " $1
     while (command | getline output > 0) if (output ~ /inet addr/) print $1, output }
     { close(command) }'

while循环用于读取ifconfig的所有输出。如果找到匹配项,则会打印该行。