0

I would like to search the file with GREP for the "User-Agent: UA" and then extract the closest line above that has "Via:" My problem is that sometimes there are multiple lines with "Via:", but I need only last one.

For example file to parse:

Via: 1.1.1.1  
not relevant line  
...
not relevant line N
User-Agent: UA
...
Via: 2.2.2.2
Via: 3.3.3.3
not relevant line
...
not relevant line N
User-Agent: UA
...
Via: 4.4.4.4
Via: 5.5.5.5
Via: 6.6.6.6
not relevant line
...
not relevant line N
User-Agent: UA

Result I want is the lines that contain "Via:" closest to "User-Agent: UA"

Via: 1.1.1.1
Via: 3.3.3.3
Via: 6.6.6.6

Any help will be appreciated.

migrated from serverfault.com Jun 2 '16 at 15:06

This question came from our site for system and network administrators.

4

You could do it with awk like so:

 awk '/Via/ {via_line=$0} /User-Agent: UA/ {print via_line}' input_file

so we'll find every line that contains Via and store that line, overwriting any previous one, then when we find the User-Agent: UA line print whatever we have stored for the Via lines.

  • You're right, === were not part of output, edited question. Your solution works like charm! – Orest Orestovych May 27 '16 at 18:01
  • @OrestOrestovych glad to help. If that solved your problem you can accept the answer by clicking the check mark by it, that will let others who find your question know what worked for you, let others know you've already found an answer, and you and I will each get some reputation for it – Eric Renouf May 27 '16 at 22:24
2

With sed:

sed -n '/^Via/h;/^User-Agent: UA$/{g;p;}' file

Output:

Via: 1.1.1.1  
Via: 3.3.3.3
Via: 6.6.6.6

Suppress automatic printing of pattern space with -n. If a line starts with Via copy pattern space to hold space (h). This overwrites hold space. If a line contains "User-Agent: UA" copy hold space to pattern space (g) and print pattern space (p).

  • Use the negated form to golf it shorter: sed '/^Via/h;/^User-Agent: UA$/!d;x' – don_crissti Jun 2 '16 at 15:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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