Reputation:
I need to get a line from a commands output that is assigned to a bash variable.
#Gets the netstat values for the UPD packages
UDP_RAW_VALUE=`netstat -su`
##TRYING THIS BUT TOTALLY FAILED.
echo "$UDP_RAW_VALUE" | sed -n "$2"p
I just need to get a specific value from one of the command executions, which is
UDP_RAW_VALUE=`netstat -su`
The output of this specific command is like this:
-bash-4.2$ bash MyBashScript
IcmpMsg:
InType0: 14464
InType3: 12682
InType8: 101
InType11: 24
OutType0: 101
OutType3: 34385
OutType8: 15840
Udp:
931752 packets received
889 packets to unknown port received.
0 packet receive errors
1007042 packets sent
0 receive buffer errors
0 send buffer errors
IgnoredMulti: 647095
UdpLite:
IpExt:
InMcastPkts: 1028470
InBcastPkts: 552859
InOctets: 233485843587
OutOctets: 75548840236
InMcastOctets: 44792084
InBcastOctets: 167490770
InNoECTPkts: 317265390
InECT0Pkts: 25289
InCEPkts: 686361
Simply, I need to read the numeric value of the 931752 packets received result, excluding the "packets received" part. I have tried doing some regular expression. Then found this sed which looks promising but I have no idea how to use it, in terms of regular expression. I am pretty sure I need to complete this with regex.
I need the numerical value because I will compare a previous and current value and check if the difference is between the threshold. If not, send the mail.
Upvotes: 1
Views: 887
Reputation: 8412
perhaps another sed solution if you dont mind?
UDP_RAW_VALUE=`netstat -su|sed -n '/Udp/{n;s/[^0-9\n]//g;p}'`
/Udp:/
#find all lines that have Udp
n
# get the next line
delete all all characters leaving you number
p
#print
or awk
UDP_RAW_VALUE=`netstat -su|awk '$0~/Udp:/{getline;print $1}'`
Upvotes: 1
Reputation: 2656
Just add this:
PACKETS_RECEIVED=$(echo "${UDP_RAW_VALUE}" | sed -n 's/^ *\([0-9][0-9]*\) packets received$/\1/p')
It will print the content that you saved from the RAW output of the command. the ""
are important or it will print all the output in one line which is not what you want.
The sed command -n says do not print the lines by default.
the s///p
command tells is to substitute the pattern between the first two /
/
with the \1
, which is the group in the pattern that is between \(
and \)
; in our case that would be the number you want.
The PACKET_RECEIVED=$()
part tells bash to run what is between the $()
and assign the output to the variable.
Upvotes: 1