Watch 10 video solutions for Tenth Line, a easy level problem involving Shell. This walkthrough by Greg Hogg has 2,093,870 views views. Want to try solving it yourself? Practice on FleetCode or read the detailed text solution.
Given a text file file.txt, print just the 10th line of the file.
Example:
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
Problem Overview: The task is simple: read a file named file.txt and output only the tenth line. If the file has fewer than ten lines, nothing should be printed. The challenge mainly tests familiarity with shell text-processing utilities and basic file iteration.
Approach 1: Line-by-Line Reading (O(n) time, O(1) space)
This approach reads the file sequentially and keeps track of the current line number. You iterate through each line, increment a counter, and print the line when the counter reaches 10. The key insight is that you never need to store the entire file in memory—only the current line and the counter. This makes the method memory efficient and practical even for very large files. Languages like Python, Java, C++, or JavaScript typically implement this with a loop over file input streams or buffered readers. The scan stops as soon as the tenth line is found, which keeps the logic simple and efficient for general file processing tasks.
Approach 2: Using Shell Commands (O(n) time, O(1) space)
Shell utilities are optimized for line-based text processing. Tools like sed, awk, and combinations of head and tail can extract a specific line directly from the command line. For example, sed -n '10p' file.txt prints only the tenth line, while awk 'NR==10' checks the current record number and outputs the matching line. Another option is head -n 10 file.txt | tail -n 1, which first truncates the file to the first ten lines and then selects the last of them. These utilities internally iterate through the file once, giving an overall time complexity of O(n) and constant memory usage. This approach is common in command-line scripting and log analysis.
Recommended for interviews: Interviewers usually expect familiarity with standard shell tools like sed or awk. Showing the line-by-line iteration demonstrates understanding of the underlying logic, but the shell command solution shows practical command-line proficiency. Both run in linear time with constant memory, but the shell approach is typically considered the most idiomatic for this problem.
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Line-by-Line Reading | O(n) | O(1) | When implementing the logic in general-purpose languages like Python, Java, or C++ |
| Shell Commands (sed / awk / head+tail) | O(n) | O(1) | Best for shell scripting, quick command-line processing, and typical interview expectations for shell problems |