Reputation: 359
I have file with following content
4 packets transmitted, 2 received, 50% packet loss, time 2002ms
rtt min/avg/max/mdev = 0.904/1.108/1.235/0.148 ms
Now I am trying to find the packet loss percentage and received value
loss=`more file.txt | grep "% packet loss" | awk -v RS=[0-9]+ '{print RT+0;exit}'`
But it always returns me the 4 ( first number in the line). But I am expecting loss to be 50% and received to be 2
Upvotes: 1
Views: 273
Reputation: 203532
Is this all you're trying to do?
$ awk '/% packet loss/{print $6, $4}' file
50% 2
and if you need them separately:
$ arr=( $(awk '/% packet loss/{print $6, $4}' file) )
$ echo "${arr[0]}"
50%
$ echo "${arr[1]}"
2
Upvotes: 0
Reputation: 85590
Why would need to make things hard using RS
and using cat .. | grep
when awk
can just solve the problem with just regex match. Just do
awk 'match($0, /.*([0-9]) received, ([0-9%]+)/, arr){ print "received="arr[1]; print "loss="arr[2] }' file.txt
Storing it in a shell variable, e.g. on bash
supporting process-substitution
read -r received loss < <(awk 'match($0, /.*([0-9]) received, ([0-9%]+)/, arr){ printf "%d %s", arr[1]+0, arr[2] ; }' file)
Upvotes: 3