Problem Description
Given a text file file.txt, output only the 10th line. If the file contains less than 10 lines, no output is expected (or an empty output depending on implementation). There are multiple valid strategies to solve this problem using shell scripting.
Key Insights
- Utilize built-in text processing commands available in Unix/Linux shells.
- Common solutions include using sed (sed -n '10p'), awk (awk 'NR==10'), or combination of head and tail commands.
- Consider edge cases where the file may have fewer than 10 lines.
Space and Time Complexity
Time Complexity: O(n) in the worst-case scenario, where n is the number of lines processed. Space Complexity: O(1) since we only need to track the current line number during processing.
Solution
This problem can be approached by directly reading the file line by line and outputting the 10th line. In shell, commands such as sed, awk, or the head-tail combination are used for a succinct solution. The algorithm involves:
- Iterating over each line of the file.
- Keeping a counter until the 10th line is reached.
- Printing the 10th line (if exists) and stopping further processing. The main trick is to minimize memory usage by processing lines sequentially and terminating early if possible.