Bash how to edit a variable

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.

>Solution :

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.

Leave a Reply