Extract specific words from a string

I hope someone here can help me. I have a line in a text file that looks 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 words starting with src =, PROTO = and DPT =. My goal is to get a line that looks something like this:

1.2.3.4 UDP 14000

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

+5
source share
4 answers

Using sed with groups:

sed -r 's/.*SRC=(\S+).*PROTO=(\S+).*DPT=(\S+).*/\1 \2 \3/'
+6
source

One way awk:

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

Conclusion:

1.2.3.4 UDP 14000
+2
source

, .

grep SRC= /var/log/messages |
while read mon day time kernel src dst len tos prec ttl id if proto spt dpt etc; do
    echo ${src#*=} ${proto#*=} ${dpt#*=}
done

$string ,

set -- $string
echo ${5#SRC=} ${13#PROTO=} ${15#DPT=}

$9, shift s.

+1

Usage Grep:

You can use regex grep's perlto find text. Here we look positively. Since the output is displayed on a separate line, you can use the function trto replace new linewith space.

grep -Po "(?<=SRC=)[0-9.]+|(?<=PROTO=)([A-Z]+)|(?<=DPT=)([0-9]+)" INPUT_FILE | 
tr "\n" " "

Test:

Step: 1: Using grep

[jaypal:~/Temp] grep -Po "(?<=SRC=)[0-9.]+|(?<=PROTO=)([A-Z]+)|(?<=DPT=)([0-9]+)" file
1.2.3.4
UDP
14000

Step: 2: Post output to tr

[jaypal:~/Temp] grep -Po "(?<=SRC=)[0-9.]+|(?<=PROTO=)([A-Z]+)|(?<=DPT=)([0-9]+)" file | 
tr "\n" " "
1.2.3.4 UDP 14000 
0
source

All Articles