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
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.
-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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With