Rebourn
Rebourn

Reputation: 23

grep multiple files through tail

Trying to grep a phrase out of multiple files as they are constantly populated (logs), but with hint as to which file was updated with the phrase.

For example:

grep bindaddr /vservers/*/var/log 

gets me:

/vservers/11010/var/log:bindaddr=xxx.xxx.xxx.xxx
/vservers/12525/var/log:bindaddr=xxx.xxx.xxx.xxx
/vservers/12593/var/log:bindaddr=xxx.xxx.xxx.xxx

Which is cool, but I need this for tail -f.

tail -fn 100 /vservers/*/var/log | grep bindaddr 

gets me the lines needed but no indicator in which file, so I need a mix of the two.

Upvotes: 2

Views: 1164

Answers (3)

cgnorthcutt
cgnorthcutt

Reputation: 4036

I think some people are coming to this post looking for a way to display the filename while grepping the tail of multiple files:

for f in path/to/files*.txt; do echo $f; tail $f | grep 'SEARCH-THIS';  done;

This will display an output like this

filename1.txt
 search result 1
 search result 2

filenam2.txt
 search result 3
 search result 4

...

Upvotes: 0

Mark Setchell
Mark Setchell

Reputation: 207465

Something like this to put the filename in the front of each line from tail:

#!/bin/bash
# Arrange to kill all descendants on exit/interrupt
trap "kill 0" SIGINT SIGTERM EXIT
for f in *.txt; do
    tail -f "$f" | sed "s/^/"$f": /" > /dev/tty &
done
# grep in stdin (i.e. /dev/tty)
grep bina -

Upvotes: 0

fedorqui
fedorqui

Reputation: 289735

If you use -v in tail, you get a verbose mode: from man tab --> "always output headers giving file names". This way, whenever something happens in a file, you will get the header on the preceding line.

Together with this, you can use grep -B1 to show the match + the previous line.

All together, this should do:

tail -fvn 100 /vservers/*/var/log | grep -B1 bindaddr

Test

Doing this in one tab:

$ echo "hi" >> a2
$ echo "hi" >> a2
$ echo "hi" >> a1
$ echo "hi" >> a2

I got this in the other one:

$ tail -vfn 100 /tmp/a* | grep -B1 "h"
==> /tmp/a1 <==

==> /tmp/a2 <==
hi
hi

==> /tmp/a1 <==
hi

==> /tmp/a2 <==
hi

Upvotes: 4

Related Questions