0

I am new to the world of scripting. My requirement is to write a bash script which will parse the output of ‘/usr/sbin/postqueue -p’ and get the mail queue count (highlighted number in the last line).

<Output of postqueue -p>
postqueue: warning: Mail system is down -- accessing queue directly
-Queue ID-  --Size-- ----Arrival Time---- -Sender/Recipient-------
9F34D414BA0A      304 Wed Aug  3 11:50:01  <sender>
                                         <recipient>

85F00414D434      304 Wed Aug  3 11:50:02  <sender>
                                         <recipient>

0C5E2414D435      303 Wed Aug  3 11:50:03  <sender>
                                         <recipient>

73C6041CCC47      304 Wed Aug  3 11:50:03  <sender>
                                         <recipient>

-- 1 Kbytes in 4 Requests.

So, how do I use grep to do a multi-line search? When I searched online, I got to know about pcregrep but I didn’t get which package provides that binary. (I am using RHEL7). I skimmed through the man page of grep but couldn’t find anything interesting.

Second question is, how do I use regex in bash to extract that mail queue count from the last line?

I got it to work in Python but I want to get this done in bash because I will have to modify an existing script to use this logic.

Let me know if you have any thoughts, thanks.

JNevill
  • 46,980
  • 4
  • 38
  • 63
Ram Kumar
  • 13
  • 3
  • Is it the `4` in the `-- 1 KBytes in 4 Requests` that you are after? – JNevill Aug 03 '16 at 12:08
  • 2
    There is no multiline here. If you want to match a regex on the last line, `tail -n 1 | grep regex` or more succinctly `sed -n '$/regex/p'`. To extract just the number with `sed`, try http://stackoverflow.com/questions/11568859/how-to-extract-text-from-a-string-using-sed – tripleee Aug 03 '16 at 12:08
  • Thanks for the quick response. Yes, I am after that 4. – Ram Kumar Aug 03 '16 at 12:28
  • I am not able to use tail $ tail -n 1 $output tail: invalid option -- 'p' And the output variable has: -- 1 Kbytes in 4 Requests. I will try the sed one to extract that number. – Ram Kumar Aug 03 '16 at 12:33

1 Answers1

0

To get request count from last line I would suggest using awk :

/usr/sbin/postqueue -p | tail -n 1 | awk -F" " '{print $(NF-1)}'

As for the pcregrep command, you can use sudo yum whatprovides pcregrep to see what package provides this command

Guy Altman
  • 41
  • 3
  • Thanks for the quick response Guy Altman :). It worked fine :). And pcregrep is provided by pcre-tools-8.32-15.el7_2.1.x86_64. Thank you once again :) – Ram Kumar Aug 03 '16 at 13:21