简体   繁体   中英

In Linux: Print last line of log file that starts with

I am trying to have the output of a single OS command display the last line of a log file, that starts with a specific string.

So basically I have a log file that reads:

Tom 
Paul 
Tom 
Steve 
Anthony 
Tom

I want to type a command similar to this:

tail -1 /etc/logfile | grep Steve

and have output like this: Steve

Unfortunately, the output of tail -1 only shows the last line of the log file...IF it matches. I want it to search the log file, from the bottom to the top (most recent to oldest) and print the first entry that matches the "Starts with" or grep. Thank you. I tried a bunch of combinations of tail, sed, cat and less...but I may be just doing something small wrong and missing it.

If the log is small enough that you don't care to scan it entirely, then

grep Steve etc/logfile | tail -n 1

will do your job. If the file is really big, you don't want to grep it since it will impact performance, so I will suggest building a script that read the file in reverse and stops in the first occurrence.

Just do it the other way round grep Steve /etc/logfile | tail -l grep Steve /etc/logfile | tail -l

grep Steve /etc/logfile

Gets all the lines with Steve then

tail -1

Prints the last of those.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM