AWK:需要这些声明吗?

发布于 2024-09-18 01:06:35 字数 568 浏览 7 评论 0原文

我在 Nagios bash 脚本中有以下行。它被用来获取指定网卡的上下错误率:

if=`awk -v interface="$INTERFACE" '$1 ~ "^" interface ":" { split($0, a, /: */); $0 = a[2]; print $3 " " $11 }' /proc/net/dev`

今天之前我从未使用过 awk,所以我正在寻找自己的方法。

正如我所看到的,我们将值 $INTERFACE 作为接口传递到 awk 脚本中,然后过滤以 interface: 开头的行(例如 eth0:)。然后,我们使用冒号空格作为分隔符来分割该行。然后,由于某种原因,我们在实际提取我们想要的值之前将数组中的第三个条目分配给 $0。

在我看来,语句 split($0, a, /: */) 和 $0 = a[2] 是不必要的,但我可能是错的!当我们引用 $3 和 $11 时,将 a[2] 分配给 $0 会改变什么吗?我已经尝试过没有前两条语句的脚本,并且输出是相同的,但也许有一个我错过的极端情况......

提前致谢

Rich

I have the following line in a Nagios bash script. It is being used to get the up and down error rates for the specified network cards:

if=`awk -v interface="$INTERFACE" '$1 ~ "^" interface ":" { split($0, a, /: */); $0 = a[2]; print $3 " " $11 }' /proc/net/dev`

I've never worked with awk before today, so I'm finding my way a bit.

As I see it, we pass the value $INTERFACE into the awk script as interface, and then filter for lines beginning interface: (eg eth0:). Then, we split the line using colon-space as a separator. Then, for some reason we assign the third entry in the array to $0 before actually extracting the values we want.

It seems to me that the statements split($0, a, /: */) and $0 = a[2] are unecessary but I may be wrong! Does the assigning of a[2] to $0 change anything when we then refer to $3 and $11? I've tried the script without the first two statements and the output is the same, but perhaps there's a corner case I've missed...

Thanks in advance

Rich

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

一直在等你来 2024-09-25 01:06:35

split() 是不必要的。这与您的 awk 语句相同

awk -v interface="eth0" '$1~interface{print $3,$11 }' /proc/net/dev

,您也可以使用 shell(bash/ksh)

shopt -s extglob
var=$(< /proc/net/dev)
var="${var##*$interface:+( )}"  # remove everything until and including the interface
var="${var%%
\n'*}"  #remove from first newline onwards
set -- $var  
echo "$3 ${11}"

The split() is unnecessary. This is the same as your awk statement

awk -v interface="eth0" '$1~interface{print $3,$11 }' /proc/net/dev

alternatively, you can use the shell(bash/ksh)

shopt -s extglob
var=$(< /proc/net/dev)
var="${var##*$interface:+( )}"  # remove everything until and including the interface
var="${var%%
\n'*}"  #remove from first newline onwards
set -- $var  
echo "$3 ${11}"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文