Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

tail and grep + print and exit first match

I'm looking for a 1 liner to tail a file and grep a "string", print the first match (new line) and exit.

I came up with:

tail -f /var/log/logfile.log -n 0 | grep -m 1 -i string_to_match

actual result is that the command prints the first match but exits only after the second match. any help would be appreciated

like image 467
Isaac A Avatar asked Jan 01 '19 08:01

Isaac A


People also ask

How do I stop grep At first match?

Limiting Output with grep -m This parameter will make grep stop matching after finding N matching lines, which works great as it will limit the output to one line, always containing the first match.

How do I get my first grep match?

-m 1 means return the first match in any given file. But it will still continue to search in other files. Also, if there are two or more matched in the same line, all of them will be displayed.

How do I grep and print previous lines?

You can use grep with -A n option to print N lines after matching lines. Using -B n option you can print N lines before matching lines. Using -C n option you can print N lines before and after matching lines. Save this answer.

How do you get 5 lines before and after grep?

For BSD or GNU grep you can use -B num to set how many lines before the match and -A num for the number of lines after the match. If you want the same number of lines before and after you can use -C num . This will show 3 lines before and 3 lines after. Save this answer.


1 Answers

In Bash you could use:

$ grep -m 1 string_to_match <(tail -n 0 -f file)

This could work for testing (NOTICE: IT APPENDS TO A FILE NAMED file):

$ grep -m 1 foo <(tail -n 0 -f file) & sleep 2 ; echo -e bar\\nfoo >> file
[1] 5390
foo
[1]+  Done                    grep --color -m 1 foo <(tail -n 0 -f file)

Edit: Further testing revealed that tail stays running in the background but exits after the next line in the file.

like image 71
James Brown Avatar answered Sep 22 '22 18:09

James Brown