0

In a log there are lines such as

20:01:59:008    46ffd700        ETH - Total Speed: 126.291 Mh/s, Total Shares: 33, Rejected: 0, Time: 00:09

I would like to use grep & tail to get the most recent line containing "ETH - Total Speed" but would only like to output 126.291

How can this be accomplished?

RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
sealfab
  • 489
  • 2
  • 6
  • 10
  • what have you tried to solve this? `tac + sed` would be easier than `grep`.. – Sundeep Jun 12 '17 at 01:58
  • Various combinations of tail -f ~/mine.log | grep, how would it be done with sed? – sealfab Jun 12 '17 at 02:24
  • add more than few lines of sample to question and expected output for that... also add what you have tried to question instead of comment.... since you are using `tail -f` I am not sure what to suggest.. you'll need some kind of solution which takes care of buffering too... https://stackoverflow.com/questions/13858912/piping-tail-output-though-grep-twice – Sundeep Jun 12 '17 at 02:31

1 Answers1

0

Let's say we want to output the first matched "ETH - Total Speed"* value among the last 20 lines and perform this while the file grows:

tail -f -n 20 logfile | grep --line-buffered -Po -m 1 'ETH - Total Speed: \K\S+(?= Mh/s)'

The result should be printed like below:

126.291

Details:

  • --line-buffered - use line buffering on output. This can cause a performance penalty
  • -P - enables PCRE

  • -m 1 - stop reading the file after the 1st matching line

RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
  • thanks, this gives the expected output. Im trying to use this is a custom zabbix item. When run in a terminal it waits until the next time that occurs in the log to output so when run via zabbix agent it times out. How can it output the last found match as opposed to waiting until the next match occurs? – sealfab Jun 12 '17 at 11:49
  • I believe the -n option is what causes this behavior, since the log might accumulate more than 20 lines that do not contain a match. I got it to work using tac logfile | grep -Po 'ETH - Total Speed: \K\S+(?= Mh/s)' | head -1 I can use tac for now but is there a way to do this with tail? – sealfab Jun 12 '17 at 12:14
  • thanks, can you help me understand the what the difference between "last found" and "most recent" is I thought it was the same thing – sealfab Jun 12 '17 at 12:59
  • in that case you can't get the last line for buffered output. My solution won't help you in that special case – RomanPerekhrest Jun 12 '17 at 13:36