I have an issue running through log files.

I'm looking to use ls to create a list of files in the log directory and grep to run through for the specific instances/times the file ran. I only want to have the last line of each file so I want the tail -1 command to run off the list of files grep provided.

I've tried multiple combinations of code that I've run across but have not had any luck so far; at this point it has become more of a curiosity than useful due to the amount of time I've spent on this. Below are a couple examples of the instances I have attempted:

ls | grep 2011_.._.._.._35_.* | tee >(tail -1)
ls | tee >(grep 2011_.._.._.._35_.*) | tail -1

Additionally, I would like to do this with a single command line if possible rather than creating a script and running a loop.

1 Answer 1



had overread that you only want the last line of each logfile ...

The command you need is xargs not tee:

 ls | grep '2011_.._.._.._35_.*' | xargs -n 1 -- tail -1


 ls -1 2011_??_??_??_35_* | xargs -n 1 -- tail -1

This calls the command tail -1 for each file that passes the grep command (1st case) or that is found by the ls command (2nd case). Note that this will not work if a file contains spaces or newline. If you need an answer for that case, add a comment.

EDIT For your comment:

ls -1 2011_??_??_??_35_* | xargs -n 1 -I FILE -- sh -c 'echo ; echo "FILE"; tail -1 "FILE"'

A little bit more complicated, but also handles files with spaces in the name.

Each "FILE" in the command sequence echo ; echo "FILE"; tail -1 "FILE" will be replaced by a line that ls outputs. This command sequence will be passed to a shell and then executed.

  • This works great to extrapolate the last line from each file, thank you for the quick response. Is there also any way to have it list the file it has taken the last line from prior to the last line listed or is the output limited to the the individual pulled line.
    – nrdk
    Nov 3, 2011 at 17:08
  • This works perfectly, thank you for the quick response and all the help
    – nrdk
    Nov 3, 2011 at 17:23
  • +1. Upvoted, although parsing ls is not a good idea in general. But since this answer "worked perfectly" for the Original Poster, it deserves some appreciation. Too bad the OP went inactive and never formally accepted your answer. Oct 23, 2017 at 4:29

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .