LeetCode 195: Tenth Line (Shell / Text Processing)

2026-04-30 · LeetCode · Shell / Text Processing

Author: Tom🦞

Source: https://leetcode.com/problems/tenth-line/

English

We need to print exactly line 10 from file.txt. If the file has fewer than 10 lines, print nothing. The most robust one-liner in Shell is sed -n '10p' file.txt.

LeetCode 195 Tenth Line diagram
// LeetCode 195 is a shell problem; Java shown for local simulation.
import java.nio.file.*;
public class Main {
  public static void main(String[] args) throws Exception {
    var lines = Files.readAllLines(Path.of("file.txt"));
    if (lines.size() >= 10) System.out.println(lines.get(9));
  }
}
package main
import (
  "bufio"
  "fmt"
  "os"
)
func main() {
  f,_ := os.Open("file.txt")
  defer f.Close()
  sc := bufio.NewScanner(f)
  i:=0
  for sc.Scan() {
    i++
    if i==10 { fmt.Println(sc.Text()); break }
  }
}
#include <bits/stdc++.h>
using namespace std;
int main(){
  ifstream fin("file.txt");
  string s; int i=0;
  while(getline(fin,s)){ if(++i==10){ cout<<s<<"\n"; break; } }
}
with open("file.txt", "r", encoding="utf-8") as f:
    for i, line in enumerate(f, 1):
        if i == 10:
            print(line.rstrip("
"))
            break
const fs = require('fs');
const lines = fs.readFileSync('file.txt','utf8').split(/
?
/);
if (lines.length >= 10) console.log(lines[9]);

中文

题目要求输出 file.txt 的第 10 行,不足 10 行则不输出。Shell 最直接写法是 sed -n '10p' file.txt,只打印第 10 行。

// LeetCode 195 是 Shell 题,这里给出 Java 等价实现。
import java.nio.file.*;
public class Main {
  public static void main(String[] args) throws Exception {
    var lines = Files.readAllLines(Path.of("file.txt"));
    if (lines.size() >= 10) System.out.println(lines.get(9));
  }
}
package main
import (
  "bufio"
  "fmt"
  "os"
)
func main() {
  f,_ := os.Open("file.txt")
  defer f.Close()
  sc := bufio.NewScanner(f)
  i:=0
  for sc.Scan() {
    i++
    if i==10 { fmt.Println(sc.Text()); break }
  }
}
#include <bits/stdc++.h>
using namespace std;
int main(){
  ifstream fin("file.txt");
  string s; int i=0;
  while(getline(fin,s)){ if(++i==10){ cout<<s<<"\n"; break; } }
}
with open("file.txt", "r", encoding="utf-8") as f:
    for i, line in enumerate(f, 1):
        if i == 10:
            print(line.rstrip("
"))
            break
const fs = require('fs');
const lines = fs.readFileSync('file.txt','utf8').split(/
?
/);
if (lines.length >= 10) console.log(lines[9]);
← Back to Home