I have got a log file with specific String
"Received bla bla with count {} 23567"
Need to get the specific number which is at the end of line. We can use awk or grep , not able to get this using below command.
grep "Received bla bla" logfile.log | grep '[0-9]'
Since the log file has timestamp at the beginning.
Advertisement
Answer
Awk lets you easily grab the last element on a line.
awk '/Received bla bla/ { print $NF }' logfile.log
The variable NF
contains the number of (by default, whitespace-separated) fields on the current line, and putting a dollar sign in front refers to the field with that index, i.e. the last field. (Conveniently, but slightly unusually for Unix tools, Awk indexing starts at 1, not 0.)
If the regex needs to come from a variable, try
awk -v regex='Received bla bla' '$0 ~ regex { print $NF }' logfile.log
The operator ~
applies the argument on the right as a regex to the argument on the left, and returns a true value if it matches. $0
is the entire current input line. The -v
option lets you set the value of an Awk variable from outside Awk before the script begins to execute.