Tenth Line - Problem
Your mission: Extract the 10th line from a text file named file.txt. Sounds simple? It is! But there are several elegant ways to accomplish this task using shell commands.

What you need to do:
โ€ข Read from a file called file.txt
โ€ข Print only the 10th line of that file
โ€ข Handle cases where the file might have fewer than 10 lines

Example:
If file.txt contains:
Line 1
Line 2
...
Line 10
Line 11


Your output should be: Line 10

Input & Output

basic_file.txt
$ Input: file.txt contains: Line 1 Line 2 Line 3 Line 4 Line 5 Line 6 Line 7 Line 8 Line 9 Line 10 Line 11 Line 12
โ€บ Output: Line 10
๐Ÿ’ก Note: The file has more than 10 lines, so we successfully extract the 10th line
exactly_ten_lines.txt
$ Input: file.txt contains: First Second Third Fourth Fifth Sixth Seventh Eighth Ninth Tenth
โ€บ Output: Tenth
๐Ÿ’ก Note: The file has exactly 10 lines, so the 10th line is the last line
fewer_lines.txt
$ Input: file.txt contains: Only line 1 Only line 2 Only line 3
โ€บ Output: (no output)
๐Ÿ’ก Note: The file has fewer than 10 lines, so there's no 10th line to print

Visualization

Tap to expand
file.txt1: First line2: Second line3: Third line...10: Target line11: Next line...head + tailPipeline approachsed -n '10p'Direct addressingawk 'NR==10'Conditional matchingOUTPUTTarget line(Content of line 10)๐ŸŽฏ Goal: Extract line 10 efficientlyโ€ข sed: Most direct and efficientโ€ข awk: Most flexible and readableโ€ข head+tail: Most intuitive for beginners
Understanding the Visualization
1
File Structure
Text file consists of sequentially numbered lines
2
Line Addressing
Different tools offer various ways to target specific lines
3
Extraction
Output only the content of the 10th line
Key Takeaway
๐ŸŽฏ Key Insight: While all approaches work, `sed -n '10p'` provides the most efficient solution with direct line addressing, avoiding unnecessary data processing and offering the cleanest syntax for this specific task.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n)

Reads lines sequentially until line 10, then exits

n
2n
โœ“ Linear Growth
Space Complexity
O(1)

Constant space usage with early termination

n
2n
โœ“ Linear Space

Constraints

  • The file is named file.txt
  • Each line contains at most 1000 characters
  • The file may have anywhere from 0 to 106 lines
  • Handle gracefully when file has fewer than 10 lines
Asked in
Google 12 Amazon 8 Meta 6 Microsoft 5
24.0K Views
Medium Frequency
~5 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen