Tenth Line - Problem

Given a text file file.txt, write a shell command or script to print just the 10th line of the file.

Note: If the file has fewer than 10 lines, the output should be empty (nothing printed).

Input & Output

Example 1 — File with 15 lines
$ Input: file.txt contains 15 lines, line 10 is "tenth line content"
Output: tenth line content
💡 Note: The file has more than 10 lines, so we successfully extract and print the 10th line
Example 2 — File with exactly 10 lines
$ Input: file.txt contains exactly 10 lines, line 10 is "last line"
Output: last line
💡 Note: The file has exactly 10 lines, so line 10 exists and is printed
Example 3 — File with fewer than 10 lines
$ Input: file.txt contains only 5 lines
Output:
💡 Note: The file has fewer than 10 lines, so there's no 10th line to print (empty output)

Constraints

  • The file may contain 0 to any number of lines
  • Each line can be up to 1000 characters
  • If file doesn't exist or has fewer than 10 lines, output should be empty

Visualization

Tap to expand
Tenth Line - AWK Solution INPUT file.txt (15 lines) 1 2 3 4 5 6 7 8 9 10 tenth line content 11 12 ... 15 Target: Line 10 ALGORITHM STEPS 1 Read File AWK reads line by line 2 Track Line Number NR = current line number 3 Check Condition NR == 10 ? Print : Skip 4 Exit After Match Stop processing early awk 'NR==10' file.txt or: sed -n '10p' file.txt Lines 1-9: skip | Line 10: print Lines 11-15: skip (exit) FINAL RESULT Line 10 extracted: tenth line content OK - Success Edge Cases: If file has < 10 lines: --> Output is empty --> No error thrown stdout: tenth line content Key Insight: AWK's NR (Number of Records) variable automatically tracks the current line number. The pattern NR==10 matches only line 10, and AWK's default action prints the matching line. Time: O(n) worst case, but exits early at line 10 | Space: O(1) - processes one line at a time TutorialsPoint - Tenth Line | AWK Line Processing Approach
Asked in
Unix Systems 30 DevOps 25
31.2K 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