Server Fault is a question and answer site for system and network administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I want to filter some of the mail IDs returned by mailq (Postfix). However, the format is not very "grep-friendly", since the information for a single mail spans multiple lines:

  9F701869D2     1356 Mon Aug 23 12:13:43  some@sender
  (host[] said: 450 4.1.1 some error message)

  9437586CF4     3153 Sat Aug 21 09:36:40  some@other.sender
  (host[] said: 450 4.1.1 some error message)

What's the easiest way to get, for example, all mail IDs where some particular error code occurred? Maybe by removing the (single) newlines, then greping and then cuting? Or by using some other, more suitable tool?

Please explain your answer. My main interest is not a copy-and-paste solution for my current problem (filtering by error code), but rather understanding how to easily parse such multi-line output.

share|improve this question
awk is the tool you want. – Paul Tomblin Aug 25 '10 at 12:00
@Paul: Since awk has quite a learning curve, could you provide a small example for mailq parsing as an answer? – Heinzi Aug 25 '10 at 12:29
In the postsuper man page there is an example of using awk to parse the mailq. – Paul Tomblin Aug 25 '10 at 12:34
@Paul: Great, thanks! – Heinzi Aug 25 '10 at 12:37
up vote 2 down vote accepted

What about:

grep -C 1 said:

-C is context and returns one line before & after "said:". Also, for future reference, -A is for after, -B is for before.

grep -C 1 said: | grep ^[0-9] | cut -f1 -d " "

(for the list of IDs)

If you need something more complex, then you would have to use awk.

share|improve this answer
Thanks, so far, it works great for my purposes. – Heinzi Aug 25 '10 at 12:41

I would use Perl and the Postfix::Parse::Mailq module.
If you don't know Perl it won't be very easy to right the good script but feel free to ask help.
If you are interested on how the module parse the output check the source

share|improve this answer
Thanks, that will be useful once I need to parse for more complex things! – Heinzi Aug 25 '10 at 12:40

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.