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

tripleee
  • 158,107
  • 27
  • 234
  • 292
Isaac A
  • 93
  • 1
  • 8
  • See this: https://stackoverflow.com/questions/5024357/do-a-tail-f-until-matching-a-pattern which also has a link to Superuser with more solutions. – James Brown Jan 01 '19 at 09:42
  • 2
    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. – Charles Duffy Jan 01 '19 at 16:17

1 Answers1

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.

James Brown
  • 34,397
  • 6
  • 36
  • 56