0

I need to be able to read the second last line of all the files within a specific directory.

These files are log files and, that specific line contains the status of tasks that ran, 'successful', 'fail', 'warning'.

I need to pull this to dump it after in reports.

At this stage i am looking only to pull the data, so the entire line, and will worry about the handling after.

As the line numbers are not set, they are irregular, I am looking at doing it with a 'while' loop, so it goes through the whole thing, but i am actually not getting the last 2 lines read, and also, i can read 1 file not all of them.

Any ideas on a nice little script to do this?

And anyone knows if this can be just done with just a linux command?

4
  • Have a look at this Shell/Bash Command to get nth line of STDOUT for different approaches. Commented Apr 9, 2015 at 9:59
  • @AlbertoZaccagni He doesn't want to process STDOUT, he wants to loop over all the files in a directory. Commented Apr 9, 2015 at 10:00
  • I know he doesn't want to process STDOUT, nonetheless the answers in that question provide lots of different ways to achieve the core problem OP is having. But probably is not meaningful to vote to close this, I'll retract my vote. Commented Apr 9, 2015 at 10:02
  • Thanks guys, i want to go through all txt files in a directory, and read all lines in each of this files and say, at this stage, just echo the second last line, as last is always 'end of log' Commented Apr 9, 2015 at 10:07

1 Answer 1

0

Use the tail command to get the last 2 lines, and then the head command to get the first of these:

for file in $DIR/*; do
    tail -2 "$file" | head -1
done
Sign up to request clarification or add additional context in comments.

3 Comments

Perhaps you want to prepend the file name as well? echo -n "$file: " before the tail command, or something like that?
It's not clear from the question whether he needs that or not
Nice, thanks Barmar. I was actually truing to do something like this but 'while read line' but was getting only to read a single file. Cheers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.