Riyaz
Riyaz

Reputation: 127

search for a string and print next to that using sed/awk?

i am newbie to sed/awk scripts.
i want to search for a string and if matches then print next word to that.

i.e my output is RXpackets:1000 and TXpackets:2000.

Using sed/awk script i want to search, and store values RXpackets and TXpackets values into variables. That means 1000 and 2000 values. can anybody help me please ?

Also suggest me which script awk/sed is best to learn and use.

Upvotes: 1

Views: 2691

Answers (4)

jgb
jgb

Reputation: 1214

I would recommend to fetch the values from /proc/net/dev instead of pulling them out with ifconfig etc.

Example:

#!/bin/sh
iface=eth0
read RXp TXp <<< $(grep $iface /proc/net/dev | awk '{ print $3, $11 }')

echo "$RXp packages received"
echo "$TXp packages sent"

Upvotes: 1

Barmar
Barmar

Reputation: 781974

Try this:

sed -n '/[RT]Xpackets/s/.*[RT]Xpackets: *\([0-9]*\).*/\1/p'

Since this just prints the numbers, you can't tell which is which. You could use separate commands for RXpackets and TXpackets to get them by themselves (changing the lines is left as an exercise for the reader).

Upvotes: 0

Vijay
Vijay

Reputation: 67301

You can use perl for this:

perl -lne 'push @a,/[RT]Xpackets:(\d+)/g;END{print "@a"}'

tested below:

> echo "my output is RXpackets:1000 and TXpackets:2000" | perl -lne 'push @a,/[RT]Xpackets:(\d+)/g;END{print "@a"}'
1000 2000
>

In what format do you need the output?

Upvotes: 0

jaypal singh
jaypal singh

Reputation: 77155

You can iterate over the line and when you find the keywords you capture the next word to it.

... | awk -F: '{for(i=1;i<=NF;i++) if($i~/RXpackets|TXpackets/) print $i"="$(i+1)}'

Upvotes: 1

Related Questions