Search code examples
bashshellheadtail

Get the nth line from the bottom "safely"


Given a file:

dept4.abc.edu
dept3.abc.edu
dept2.abc.edu
dept1.abc.edu

I know how to get the 3rd line from the bottom using the command:

tail -3 file | head -1

This is okay as long as the file length is greater or equal 3 lines [ $(wc -l < file) -gt 3 ]. So tail -4 file | head -1 is still fine, but tail -5 file | head -1 is not what I really want.

I am wondering if there is a better way and cleaner way in getting the nth line safely, by saying safely I mean if it is not there, just return me an empty string or error. Any ideas?


Solution

  • There are many ways to get the nth line from a file, see e.g. Bash tool to get nth line from a file

    The simplest way to get the nth line from the bottom of the file is to use tac (inverse of cat) to reverse the file. Something like this:

    tac file | sed '3q;d'