0

I have a file with quite many lines, and I would need the nth last line (specifically the 95th from bottom). How could I go on about doing this? One way would be to use tail but then it prints everything from last to 95th last, when I would only need the 95th.

1
  • Here is another easy way to do this using tac file | awk 'NR==95' Nov 23 '21 at 8:53
4

As you noted, you can use tail to get the last 95 lines from a file. You just want the first of these, for which there is a utility called head. So

tail -95 file | head -1

Using tail is probably the best you can do.

Another approach would be to read the lines into an array of lines, and just print out the n-95 line when you get to the end of the file. You don't actually need to store all the lines so you can have a circular buffer with 95 elements to store the last 95 lines you have read.

1
  • Thanks! This seems to have worked in this case! :) Nov 23 '21 at 8:47
4

The answer of @icarus does the trick, but just to add another option:

tac file | sed -n 95p

tac will print the file in reverse, and sed -n 95p will print the 95th line. Since the file is printed in reverse, it will show the 95th line from the bottom.

Update

As @icarus mentioned in the comments:

A downside is that the whole file is passed through the pipe, rather than just 95 lines. Telling sed to explicitly quit after printing the 95th line would remove this disadvantage.

So here's an updated command that quits after it prints the 95th line:

tac file | sed -n '95{p; q}'
1
  • This is indeed another way to do it. It has the advantage that if the file is shorter than 95 lines it will output nothing, rather than the first line. A downside is that the whole file is passed through the pipe, rather than just 95 kines. Telling sed to explicitly quit after printing the 95th line would remove this disadvantage.
    – icarus
    Nov 23 '21 at 16:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.