Using tee to pipe ls and grep output into tail command without a script

1

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.

nrdk

Posted 2011-11-03T15:49:11.330

Reputation: 11

Answers

1

REVISED!

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

or

 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.

ktf

Posted 2011-11-03T15:49:11.330

Reputation: 2 168

+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.

– Kamil Maciorowski – 2017-10-23T04:29:00.150

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 – 2011-11-03T17:08:56.540

This works perfectly, thank you for the quick response and all the help – nrdk – 2011-11-03T17:23:29.627