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
In #195 Tenth Line, the goal is to print the 10th line from a text file using common Shell utilities. Since files are read sequentially in most command-line tools, the typical strategy is to process the file line by line until the desired line number is reached.
A practical approach is to use tools such as sed, awk, or a combination of commands like head and tail. These utilities allow filtering or selecting specific line numbers efficiently. For example, some commands can directly match the line number while scanning the file, stopping once the 10th line is identified.
The key idea is to avoid storing the entire file in memory. Instead, rely on streaming behavior provided by Unix text-processing tools. This keeps memory usage minimal while ensuring the program only reads the necessary portion of the file. In most implementations, the file is scanned until the target line is encountered.
Time Complexity: O(n) where n is the number of lines processed (up to the 10th line in optimized cases). Space Complexity: O(1) since no additional data structures are required.
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| Using line filtering tools (sed/awk) | O(n) | O(1) |
| Using head and tail combination | O(n) | O(1) |
Greg Hogg
Watch expert explanations and walkthroughs
Jot down your thoughts, approach, and key learnings
While the exact problem may not always appear in interviews, similar questions testing command-line proficiency and text processing are common. Understanding tools like sed, awk, and pipes is useful for system and scripting roles.
No special data structure is required for this problem. Shell commands process the file as a stream, reading it line by line, which keeps memory usage constant and efficient.
The optimal approach is to use a Unix text-processing utility that can directly access or filter by line number, such as sed or awk. These tools read the file sequentially and print the target line without storing the entire file in memory.
Yes, a common strategy combines standard utilities such as head and tail. One command limits the file to the first few lines, while the other extracts the final line from that subset.