Question: How do I find the nth line in a file in Linux command line?
Answer: There could be a number of ways to do that. For example, you can use a combination of head and tail command in the following function:
head -n x file_name | tail -n 1
You can replace x with the line number you want to display.
Explanation: You probably already know that head command gets the lines of a file from the start while the tail command gets the lines from the end.
The “head -n x” part of the command will get the first x lines of the files. It will then pipe this output to the tail command. The tail command will display the first line from the bottom.
Quite obviously, if you take 10 lines from the top, the first one from the bottom will be the 10th line. That’s the logic behind this command.
However, keep in mind that your file must have at least n number of lines. Otherwise, it will result in an incorrect answer.
Alternative: An alternative to the above command would be to use sed. For example, to display the 10th line, you can use sed in the following manner:
sed -n '10p' file.txt
The -n suppresses the output while the p command prints specific lines.
I hope this quick Linux command trick helped you to find the nth line of a file.