0

I have a file where data packets comes at high speed. I want to extract all packets from main file to another file after finding ip.

Main file "Main.cap" -

Device:A
Host:B
IP:0.0.0.0
Time:123654

Device:B
Host:C
IP:1.1.1.1
Time:125423


Device:C
Host:D
IP:1.1.1.1
Time:129423


Device:E
Host:F
IP:1.1.1.1
Time:125423


Device:G
Host:H
IP:1.2.5.6
Time:12543

Now from this file if i want to extract all packets from IP 1.1.1.1 i.e. all 4 fields and all 3 packets then what should be done?

In short we have to grep this ip 1.1.1.1 and then find 2 new lines,one above this ip and one after ip.

user2663468
  • 85
  • 1
  • 8
  • 1
    possible duplicate of [grep a file, but show several surrounding lines?](http://stackoverflow.com/questions/9081/grep-a-file-but-show-several-surrounding-lines) – fedorqui 'SO stop harming' Jul 17 '14 at 13:19
  • @fedorqui- Thanks for the link, can you please confirm, will it give all the packets from the file? say if i do `grep 1.1.1.1 -B 2 -A 1 Main.cap > output.txt` then all packets will come? – user2663468 Jul 17 '14 at 13:32
  • 1
    Test it yourself. Note it would be handy to use `grep -F "1.1.1.1"`, so that the `.` are understood as plain dot, not any character. All together, `grep -B 2 -A 1 -F "1.1.1.1" Main.cap`. – fedorqui 'SO stop harming' Jul 17 '14 at 13:38
  • @fedorqui- Thanks a lot for answer and suggestion. – user2663468 Jul 17 '14 at 13:46
  • @fedorqui- there is one edition which is size of all packets is not same so new line delimiter is must. any suggestions please? – user2663468 Jul 21 '14 at 09:43

1 Answers1

2

awk is really good at this sort of thing. As long as there is a blank line between records, you can do:

awk '/IP:1\.1\.1\.1/' ORS='\n\n' RS= input-file

Setting RS to the empty string makes awk treat blank lines as the record separator, so you just have to match the IP to print the entire record. (Use \. to match a literal .) It's not strictly necessary to assign ORS, but it makes the output prettier.

mklement0
  • 245,023
  • 45
  • 419
  • 492
William Pursell
  • 174,418
  • 44
  • 247
  • 279
  • In what way is it not working? Are your blank lines truly blank, or do they contain any whitespace? Are you using exactly the command above (cut-n-paste) or are you writing `RS=input-file`? – William Pursell Jul 21 '14 at 13:07