0

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.

2
  • 1
    You could use bash regular expressions to do this kind of parsing, but remember that the primary purpose of bash is to run other programs to do your actual data processing, not do the processing itself. Commented Jul 11, 2022 at 15:08
  • 1
    The answers given below are right. But also note that in many cases, the tool (netstat in this case) may have some command-line option to provide the output in more parsable/precise manner. My comment may not be relevant in the case of netstat, but I am just putting it out here as a note since you are new to shell scripting. :-) Commented Jul 11, 2022 at 15:17

4 Answers 4

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

2 Comments

Unnecessary grep: mbuf=$(netstat -m | awk -F/ '/mbuf clusters in use/ {print $3}')
@jordanm: I have the habit of filtering using grep and adapting the output using awk :-)
1
$ netstat -m | awk -F/ '/mbuf clusters in use/{print $3}' 
5866

Comments

0
mbuf=$( netstat -m | 
        
gawk '$_=$--NF' RS='^$' FS='/[^/]+mbuf[^/]*clusters in use.*$|[/\n]+|$' )

or

mawk -F/ '$!NF=$((NF*=/mbuf[^/]*clusters in use/)^_+NR)'
5866

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.