I need to return the most recent value from a log file. I know this value will always be near the end of the log file, and I only ever want one result.

On Ubuntu I've accomplished this with tac dhcp.log | grep macaddress -m 1, and on Solaris I've almost replicated this with tail -r dhcp.log | grep macaddress, but it runs through the entire file which is quite large and takes too long. Is there any way to kill grep after the first result so that it doesn't run through the entire file?

  • 2
    Have you tried adding a further pipe to a process such as sed '1q' or head -n1? That should send a SIGPIPE to the writing process, I think – steeldriver Aug 18 '16 at 0:46
  • I did not. I am new to unix so getting as far as I did on Ubuntu was a big win for me. I tried Jlliagre's solution below and it worked perfectly though. – John Moffitt Aug 18 '16 at 1:51
  • It's worth noting that gnu grep's -m option doesn't cause grep to SIGPIPE the sender. it just stops reading the stream, other programs are free to continue reading from it. something the awk/sed answers won't be able to replicate. – llua Aug 18 '16 at 3:20

If you have GNUgrep installed (eg /usr/bin/ggrep or /opt/gnu/bin/grep on Solaris 11, /opt/sfw/bin/ggrep on Solaris 10) then you have the -m flag.

Instead of grep you could use sed

sed -n '/macaddress/{ p
| improve this answer | |
  • I feel like this is the best answer in most cases, as ggrep would be the best possible answer. However in my case I used Jlliagre's solution as the intent of the command was clearer to me. – John Moffitt Aug 18 '16 at 1:47

Here is an alternate solution based on awk:

tail -r file | nawk '/macaddress/ {print;exit}'
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.