Search code examples
bashgrepoutputtee

Best way to get number of lines from command whilst still outputting to both Terminal and to file


I'm currently writing a simple Bash script which finds lines in files which match the target string and outputs this both to the Terminal display but also to a file. The command at the moment is:

grep -r -n -F "myname" /Users/tom/Desktop/* | tee /Users/tom/Desktop/out.txt

This code works perfectly for what I want it to do. However, I also want to have a feature that when the command has finished, it will echo the number of results (lines) that were found to contain the specified string.

What would be the best method of doing this? I understand that using:

grep -r -n -F "myname" /Users/tom/Desktop/* | tee >(wc -l)

would enable me to get the line count whilst still enabling me to view the output in the Terminal, but, it would not allow me to save the output to a file.

Thank you in advance for any help.

Kind regards, Tom

P.S. The script deals with very large files so efficiency is very important.


Solution

  • tee accepts multiple filenames to write to:

    grep -r -n -F "myname" /Users/tom/Desktop/* | tee >(wc -l) /Users/tom/Desktop/out.txt
    

    If you want to

    1. Write to a file
    2. Write to the terminal
    3. Capture the resulting number of lines

    You can use:

    lines=$(grep -rnF "myname" /Users/tom/Desktop/* |
        tee /Users/tom/Desktop/out.txt /dev/stderr |
        wc -l)