简体   繁体   中英

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 tail -4 file | head -1 is still fine, but tail -5 file | head -1 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?

There are many ways to get the nth line from a file, see eg 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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM