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:
|
|
Your script should output the tenth line, which is:
|
|
Note
- If the file contains less than 10 lines, what should you output?
- 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
|
|
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
|
|
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
|
|
Complexity
- ⏰ Time:
O(n)
- 🧺 Space:
O(1)