使用 sed 获取值

使用 sed 获取值

我正在运行一个脚本,其输出是:

Circuit                           Packets/Bytes Sent Packets/Bytes Received
2/1 vlan-id 1005                         11589119559            14650974869
                                       3084237796552         13027195853643

此脚本每五分钟运行一次,用于 MRTG 目的。现在我需要分别获取第二行第 2 列和第 3 列的值:

Bytes Sent 3084237796552

Bytes Received 13027195853643

我如何使用 sed 来实现这一点?

答案1

一个解决方案是使用sed

sed -n '$ { s/^\s*/Bytes Sent /; s/\([0-9]\)[ ]/\1\n/; s/\(\n\)\s*/\1Bytes Received /; p }' infile

解释:

-n                               # Disable printing lines.
$                                # In last line...
s/^\s*/Bytes Sent /              # Substitute all spaces from the beginning with literal string 'Bytes Sent'
s/\([0-9]\)[ ]/\1\n/             # Substitute first match of a space after a number with a new line.
s/\(\n\)\s*/\1Bytes Received /   # Substitute all space after the new line with literal string 'Bytes received'
p                                # Print this line (two lines after the included '\n')

结果:

Bytes Sent 3084237796552
Bytes Received 13027195853643

答案2

我从来没有掌握 sed 和多行,但如果你只是想完成它,这应该可行。

whatever_gives_your_data.sh | tail -1 |  awk '{ print "Bytes sent "$1 "\nBytes recieved "$2 }'

相关内容