Problem

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

Examples

Example:

Assume that file.txt has the following content:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
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:

1
Line 10

Note

  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.

Solution

Method 1 – Using sed

Intuition

sed can directly print a specific line from a file.

Approach

Use sed -n '10p' file.txt to print only the 10th line.

Code

1
sed -n '10p' file.txt

Complexity

  • ⏰ Time: O(n)
  • 🧺 Space: O(1)

Method 2 – Using awk

Intuition

awk can process files line by line and print a specific line.

Approach

Use awk 'NR==10' file.txt to print the 10th line.

Code

1
awk 'NR==10' file.txt

Complexity

  • ⏰ Time: O(n)
  • 🧺 Space: O(1)

Method 3 – Using head and tail

Intuition

Combine head and tail to extract the 10th line.

Approach

Use head -n 10 file.txt | tail -n 1 to get the 10th line.

Code

1
head -n 10 file.txt | tail -n 1

Complexity

  • ⏰ Time: O(n)
  • 🧺 Space: O(1)