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?

tux3
  • 7,171
  • 6
  • 39
  • 51
eLGusto
  • 31
  • 8
  • Have a look at this [Shell/Bash Command to get nth line of STDOUT](http://stackoverflow.com/questions/1429556/shell-bash-command-to-get-nth-line-of-stdout) for different approaches. – Alberto Zaccagni Apr 09 '15 at 09:59
  • @AlbertoZaccagni He doesn't want to process STDOUT, he wants to loop over all the files in a directory. – Barmar Apr 09 '15 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. – Alberto Zaccagni Apr 09 '15 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' – eLGusto Apr 09 '15 at 10:07

1 Answers1

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
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Perhaps you want to prepend the file name as well? `echo -n "$file: "` before the `tail` command, or something like that? – Thomas Apr 09 '15 at 10:03
  • It's not clear from the question whether he needs that or not – Barmar Apr 09 '15 at 10:04
  • 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. – eLGusto Apr 09 '15 at 10:26