Get n-th line from a file

0
568
Get n-th line from a file

In this article, I will show you some tips to get n-th line from a file using command line.

Get n-th line from a file

Rather than using a bloated text editor just to read a single line from a file, using command to query what we want is a better choice.

Assuming the input has following content:

id,title,author,created_at
1,"Backup and restore MySQLDB","Pete Houston","2018-08-27 12:15:32" 
2,"Quick guide to SQLite3","Pete Houston","2018-09-12 22:35:56" 
3,"Migrate to MongoDB","Pete Houston","2018-10-01 03:48:18"

Tt is a CSV file, but you can use any file.

Let say, we want to get 2nd line from that sample.csv. What is your solution?

Here are several useful commands.

1. Combining head and tail

This might be the first thing that comes to mind whenever we need to deal with lines from file.

$ head -n2 sample.csv | tail -1
1,"Backup and restore MySQLDB","Pete Houston","2018-08-27 12:15:32"

What it does is to grab first 2 lines, then get the last line.

2. Using sed

sed is a very powerful utility, and this is how we use it.

$ sed '2q;d' sample.csv
1,"Backup and restore MySQLDB","Pete Houston","2018-08-27 12:15:32"

It looks pretty hard to understanding if you never use sed before.

Basically, sed will iterate through each line and delete it in output, but will stop immediate when it reaches 2nd line.

Nq:means to stop immediately when it reaches N-th line.

d: means to delete current line.

So sed '12q;d' input_file will print out the 12-th line from the input_file.

3. Another head and tail

This one is pretty interesting.

$ tail -n+2 sample.csv | head -1
1,"Backup and restore MySQLDB","Pete Houston","2018-08-27 12:15:32"

It is not tail -n2, but tail -n+2 .

The option -n+NUM means to get lines starting from line NUM-th from the file. Therefore, we can use head to get the first displaying line.

Some saying that this command is being faster than the others. But it looks depending on the implementation of tail.

Conclusion

There are more and many ways to get n-th line from a file, it depends on what we know. This is a pretty interesting question that many people ask about it on Internet.

This post gets total inspiration from this question on StackOverflow.