Tenth Line
Problem
Given a text file file.txt, print just the 10th line. If file.txt has fewer than 10 lines print nothing. Canonical bash: sed -n '10p' file.txt or awk 'NR==10' file.txt.
"Line 1, Line 2, ..., Line 10"Line 10# Bash one-liner: sed -n '10p' file.txt
def tenth_line(lines):
for i, ln in enumerate(lines, start=1):
if i == 10:
return ln
return ""
// Bash one-liner: sed -n '10p' file.txt
function tenthLine(lines) {
for (let i = 0; i < lines.length; i++) {
if (i + 1 === 10) return lines[i];
}
return "";
}
// Bash one-liner: sed -n '10p' file.txt
class Solution {
public String tenthLine(List<String> lines) {
for (int i = 0; i < lines.size(); i++) {
if (i + 1 == 10) return lines.get(i);
}
return "";
}
}
// Bash one-liner: sed -n '10p' file.txt
string tenthLine(vector<string>& lines) {
for (int i = 0; i < (int)lines.size(); i++) {
if (i + 1 == 10) return lines[i];
}
return "";
}
Explanation
The whole task is to print exactly the 10th line of a file, and nothing at all if the file is shorter. The cleanest answer is a one-line shell command, but the logic underneath is just counting lines.
In bash, sed -n '10p' file.txt tells sed to stay quiet and print only line 10, while awk 'NR==10' prints the line when the record number NR equals 10. If there is no 10th line, neither prints anything, which is exactly the desired behavior.
The portable version here makes the counting explicit: walk the lines while a counter goes 1, 2, 3, ..., and the moment the counter hits 10 we return that line. If the loop ends first, we return the empty string.
This works because line numbering is simply the position in order, so the 10th line is whatever the counter labels as 10.
Example: with lines L1, L2, ..., L11, the counter reaches 10 at L10, so we print L10 and stop. A file with only 5 lines would finish the loop without ever reaching 10, printing nothing.