1

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.

2 Answers2

5

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.

Eric Renouf
  • 18,431
  • You're right, === were not part of output, edited question. Your solution works like charm! –  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
3

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).

Cyrus
  • 12,309