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'm struggling to get the correct regex to match specifically 'Contact' and 'User-Agent' only if the 'Contact' address matches 10.0.x.x in ~70GB of SIP messages.

The SIP message will always contain a 'Contact' and 'User-Agent' however these could be in any position with 'User-Agent' always after 'Contact'.

"If 'Contact' matches 10.0.x.x then grab the 'User-Agent' too".

CSeq: 756 REGISTER;branch=z9hG4bK314690454165BD2A;rport=49419;received=
Contact: <sip:43498234985@;transport=udp>;methods="INVITE, ACK, BYE,           CANCEL, OPTIONS, INFO, MESSAGE, SUBSCRIBE, NOTIFY, PRACK, UPDATE, REFER";expires=3600
Accept-Language: en-gb,en;q=0.9
User-Agent: PolycomSoundPointIP-SPIP_331-UA/
Max-Forwards: 69

I can match the contact however I just can't pull the User-Agent too.

sed -rn 's/.*(^Contact: .*?10\.0\.[0-9]{0,3}\.[0-9]{0,3}).*/\1/p' XSLog2013.01.31-23.31.29.txt

Outputs: Contact: sip:442023482890@

I get no output with:

sed -rn 's/.*(^Contact: .*?10\.0\.[0-9]{0,3}\.[0-9]{0,3}).*?(^User-Agent:.*?$).*/\1\2/p' XSLog2013.01.31-23.31.29.txt
share|improve this question

What you try to do is a multi-line matching. Multi-line regex in sed is really complex. If you can understand something like

sed -rn '/^Contacts/ h;/^User/ h;/^Contact/^User/ {s/(Con.*User)/xx/g;p;n;h};h' inputfile

and the meaning of these ; and h and n, then you have the answer.

If you don't understand, the easier way is to make a script in your favourite-language-supporting multiline regex. For example, a PHP script would be :

$contact = "";
$fp=fopen ($inputfile, 'r');
 $l = fgets($fp);
 if (preg_match('!^(Contact: .*?10\.0\.[0-9]{0,3}\.[0-9]{0,3})!', $l, $match))
  $contact = $match[1];
 if (preg_match('!^User-agent!', $l) && '' != $contact)
  echo $contact."\n".$l."\n=======\n";
  $contact = "";

then run with php -f script.php

You can also google about multiline regex in sed.

share|improve this answer

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.