tail and grep + print and exit first match
Asked Answered
P

1

5

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

Pamphleteer answered 1/1, 2019 at 8:47 Comment(2)
See this: #5024857 which also has a link to Superuser with more solutions.Melar
Heh. So, grep exits immediately, but tail doesn't know that grep exited until it tries to write a second line and gets a SIGPIPE.Directoire
M
7

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.

Melar answered 1/1, 2019 at 9:8 Comment(9)
Humm, pretty hard to make a one-liner for testing.Melar
thanks, this one gives syntax error near unexpected token `('Pamphleteer
@IsaacA: You don't use bash.Coray
@Coray GNU bash, version 3.2.57(1)-releasePamphleteer
@Tiw cant use perl :(Pamphleteer
@Coray Ive edited your suggestion to: grep -m 1 urlfilter <$(tail -n 0 -f /var/log/alert1.log) but it does not print and does not exits... just sits there....Pamphleteer
@IsaacA: I can't reproduce the error you mentioned with bash-3.2.57. It occurs when using sh.Coray
If targeting a new enough version of bash, command substitutions' PIDs will be put in $! so you can kill them explicitly, so don't need to wait for the later match/exit. I want to say that's version 4.3 or therebouts.Directoire
@JamesBrown Eventually what you suggested was the right answer for me! Thanks and thank you all! grep -m 1 string_to_match <(tail -n 0 -f /var/log/syslog.log)Pamphleteer

© 2022 - 2024 — McMap. All rights reserved.