Extract specific words from a line
14,259
Solution 1
Use Sed with groups:
sed -r 's/.*SRC=(\S+).*PROTO=(\S+).*DPT=(\S+).*/\1 \2 \3/'
Solution 2
One way using awk
:
awk 'BEGIN { FS = "[ =]" } { print $7, $22, $26 }' infile
Output:
1.2.3.4 UDP 14000
Solution 3
If the output is generated in a fixed order, then you could simply use shell builtins.
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
If you have the data in $string and the desired parameters are at fixed positions, you could also
set -- $string
echo ${5#SRC=} ${13#PROTO=} ${15#DPT=}
If your shell can't handle positional parameters beyond $9 you will need a few shift
s.
Related videos on Youtube
Author by
Jørgen
Updated on June 04, 2022Comments
-
Jørgen almost 2 years
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.
-
potong over 12 yearsYou might replace
[^ ]*
by\S*