Wednesday 31 July 2019

3 WAYS TO GET THE NTH LINE OF A FILE IN LINUX

The need to get/print a particular line of a file on the Linux shell is a common task. Luckily there are various ways to do this. Below are three great ways to get the nth line of a file in Linux.

1. head / tail

Simply using the combination of the head and tail commands is probably the easiest approach. Below is an example using head and tail to read the 25th line of sample_data_1.txt:

2. sed

There are a couple of nice ways to do this with sed. The first is with the p (print) command, and the other is with the d (delete) command. The n option with the print command is used to only print lines explicitly indicated by the command. For example, sed will output the 25th line of sample_data_1.txt with each of the commands below:

3. awk

awk has a built in variable NR that keeps track of file/stream row numbers. awk syntax and idioms can be hard to read, so below are three different ways to print line 25 of sample_data_1.txt file using awk.

0 comments:

Post a Comment