[ACCEPTED]-get a part of a line after grep-grep

Accepted answer
Score: 12

cut must do the job

grep something somewhere | grep againsomething | cut -f2 -d' '


Score: 11

Use awk(1):

awk ' { print $2" "substr($0,length($0)-8) }'


Score: 2

I'm going to argue perl is a better choice 7 than awk here:

perl -ne 'next if ! (/LATENCY|CMDTYPE=NEW/ && /^\d+.*\s+(.*)\s+.*(.{9})$/); print "$2 $3\n";'

The regex is more robust, allowing 6 you to omit lines that don't match the stricter 5 pattern. The awk scripts above are going 4 to see overflows in the substr call (I honestly 3 dont' know what negative indices do in awk) if 2 you feed it broken input like partial lines 1 from the end of a log.

Score: 2

You can do it all with grep using -o which outputs 4 only the match and not the whole line.

Assuming 3 you can create a regex for the timestamp 2 and the rest of the line, you could simply 1 add:

... | grep -o regex  

[Added answer for anyone else who lands here trying to extract part of a line using grep where the regex is the part they want to extract.]

Score: 1

You can use awk as follows:

grep LATENCY file.log | grep CMDTYPE=NEW | awk '{print $2,substr($0,length($0)-9,9)}'


Score: 0

No need to use grep, awk can do that as 1 well:

awk '/LATENCY/ && /CMDTYPE=NEW/ {print $2 " " substr($0, length($0)-8)}' file
Score: 0

You can do everything with sed alone:

$ echo "234432 12:44:22.432095 LATENCY blah CMDTYPE=NEW foo bar 123456789" | \
sed -n '/LATENCY/!b;/CMDTYPE=NEW/!b;s/^.\+\s\+\([0-9:.]\+\)\s.\+\(.........\)$/\1 \2/; p'
12:44:22.432095 123456789


More Related questions