Tenth Line

easy string bash

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.

Input"Line 1, Line 2, ..., Line 10"
OutputLine 10
Increment a counter; print the line whose counter equals 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 "";
}
Time: O(min(n, 10)) Space: O(1)