Search code examples
linuxbashgreppipetail

How to grep output from tail and include file names?


How is this:

tail -n +1 *.txt | grep foo

slightly modified to show the filename?

When it's not piped, the filename is conveniently part of the output. Can the grep operation be confined to the content of the file, while preserving that the filename is output?


Solution

  • You could use a simple regex that matches;

    • All the filename's; ==>(.*)<==
    • Your 'search' string (eg: foo)
    tail -n +1 * | grep -E '==>(.*)<==|foo'
    

    Anther option, based on my original answer by running the -exec through grep like so:

    find . -type f -print -exec grep 'foo'  {} \;
    

    Example using both methods in 3 files ({a,b,c}.txt) all containing a, b, and c.

    bash-3.2$ tail -n +1 *
    ==> a.txt <==
    a
    b
    c
    
    
    ==> b.txt <==
    a
    b
    c
    
    
    ==> c.txt <==
    a
    b
    c
    
    
    bash-3.2$ tail -n +1 * | grep -E '==>(.*)<==|c'
    ==> a.txt <==
    c
    ==> b.txt <==
    c
    ==> c.txt <==
    c
    
    
    bash-3.2$ find . -type f -print -exec grep 'c' {} \;
    ./c.txt
    c
    ./b.txt
    c
    ./a.txt
    c