1. Tenth Line

Given a text file file.txt, print just the 10th line of the file.


Assume that file.txt has the following content:

Line 1
Line 2
Line 3
Line 4
Line 5
Line 6
Line 7
Line 8
Line 9
Line 10

Your script should output the tenth line, which is:

Line 10

Attention points

Note the notes it provides. In fact, test also covers two points mentioned in notes:


  1. If the file contains less than 10 lines, what should you output?
  2. There’s at least three different solutions. Try to explore all possibilities.

Try 1

head -10 file.txt | tail -1

The disadvantage is that the default file must be greater than or equal to ten lines.

  • If the file is less than ten lines,head -10 file.txtIt will output the entire file (for example, it only has 8 lines),tail -1Then get the corresponding last line (for example, line 8).


Solution 1

head -n 10 file.txt | tail -n +10
  • head -n 10 file.txt: gets the first ten lines, or the entire file (if the file is less than ten lines).
  • tail -n +10: get everything from line 10 and after it.
   -n, --lines=[+]NUM
         output the last NUM lines, instead of the last 10; or use -n +NUM to output starting with line NUM

In this way, if the file is less than ten lines, the last line will not be output, but the output isempty

Solution 2

cat file.txt | sed -n '10p'
  • -n: display only the corresponding number of rows. If not, it will output all
  • '10p'MediumpRefer to print
   -n, --quiet, --silent
         suppress automatic printing of pattern space

   p      Print the current pattern space.

  number      Match only the specified line number (which increments  cumula‐
              tively  across  files, unless the -s option is specified on the
              command line).

Solution 3

cat file.txt | sed '10!d'
  • d: delete
   d      Delete pattern space.  Start next cycle.

Solution 4

Here are four equivalent usesawkExpression:

#awk example 1
cat file.txt | awk 'NR==10'
#awk example 2
cat file.txt | awk 'NR==10{print}'
#awk example 3
cat file.txt | awk '{if(NR==10) print}'
#Awk example 4 full version
cat file.txt | awk 'BEGIN{}; { if(NR==10) {print;} }; END{};'

References and recommended readings:



Https://leetcode.com/problems…: there are some strange solutions

This article follows the Creative Commons copyright agreement CC by-nc 4.0, which requires signature, non-commercial and consistent. It can be reproduced on the basis of CC by-nc 4.0, but please indicate the source in the form of hyperlink. The article only represents the author’s knowledge and opinions. If there are different opinions, you can reply and discuss them.