Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract specific words from a line

Tags:

sed

awk

I hope someone here can help me. I have a line in a text file looking like this:

Jan  8 14:12:56 kernel: SRC=1.2.3.4 DST=255.255.255.255 LEN=104 TOS=0x00 PREC=0x00 TTL=64 ID=0 DF PROTO=UDP SPT=44224 DPT=14000 LEN=84

I want to extract the words starting with SRC=, PROTO= and DPT=. My goal is to end up with a line looking something like this:

1.2.3.4 UDP 14000

I would prefer the solution being bash using sed, awk or similar if possible.

like image 366
Jørgen Avatar asked Jan 08 '12 13:01

Jørgen


People also ask

How do I extract certain words from a string?

We can use regular expressions in python to extract specific words from a string. We can use search() method from re module to find the first occurrence of the word and then we can obtain the word using slicing.


2 Answers

Use Sed with groups:

sed -r 's/.*SRC=(\S+).*PROTO=(\S+).*DPT=(\S+).*/\1 \2 \3/'
like image 108
Fred Foo Avatar answered Sep 17 '22 23:09

Fred Foo


One way using awk:

awk 'BEGIN { FS = "[ =]" } { print $7, $22, $26 }' infile

Output:

1.2.3.4 UDP 14000
like image 24
Birei Avatar answered Sep 17 '22 23:09

Birei