I am new to using bash. Now I am about to read a value, but the output of the console is too long and I just want to shorten it to the specific value.
netstat -m
24270/3315/27585 mbufs in use (current/cache/total)
4142/1724/5866/1000000 mbuf clusters in use (current/cache/total/max)
40/1478 mbuf clusters out of packet secondary zone in use (current/cache)
0/145/145/524288 4k (page size) jumbo clusters in use (current/cache/total/max)
0/0/0/524288 9k jumbo clusters in use (current/cache/total/max)
0/0/0/83968 16k jumbo clusters in use (current/cache/total/max)
...
Now I want to get to the 5866 in the second line and wrap it in a variable. Currently my script looks like this:
mbuf_stat=$(netstat -m)
mbuf=$mbuf_stat
mbuf=${mbuf#*)}
mbuf=${mbuf#*/}
mbuf=${mbuf#*/}
mbuf=${mbuf%%/*}
echo "$mbuf"
Is there an easier way to do this? It seems pretty complicated to me. Unfortunately, I have not found a simpler way yet.
CodePudding user response:
Use awk
for this:
mbuf=$(netstat -m | awk -F'/' 'NR == 2 { print $3; exit }')
-F'/'
makes /
the field separator. NR == 2
matches the second line of the file. print $3
prints the third field, which contains 5866
, then exit
exits the script.
CodePudding user response:
What about this:
mbuf=$(netstat -m | grep "mbuf clusters in use" | awk -F/ '{print $3}')
The difference with the answer from Barmar is that I'm looking for the line, containing "mbuf clusters in use" instead of assuming it's the second one.
CodePudding user response:
$ netstat -m | awk -F/ '/mbuf clusters in use/{print $3}'
5866
CodePudding user response:
mbuf=$( netstat -m | gawk '$_=$--NF' RS='^$' FS='/[^/] mbuf[^/]*clusters in use.*$|[/\n] |$' )
or
mawk -F/ '$!NF=$((NF*=/mbuf[^/]*clusters in use/)^_ NR)'
5866