JavaGrepコード(javacだけでコンパイル可)

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Grep {
  private String patternString;
  private String[] fileNames;

  public Grep(String patternString, String[] fileNames) {
    this.patternString = patternString;
    this.fileNames = fileNames;
  }

  public void search() {
    Pattern pattern = Pattern.compile(patternString);

    for (String fileName : fileNames) {
      try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
        String line;
        while ((line = reader.readLine()) != null) {
          Matcher matcher = pattern.matcher(line);
          if (matcher.find()) {
            System.out.println(fileName + ": " + line);
          }
        }
      } catch (IOException e) {
        System.err.println("ファイル " + fileName + " を開けませんでした: " + e.getMessage());
      }
    }
  }

  public static void main(String[] args) {
    if (args.length < 2) {
      System.err.println("使用法: java Grep <検索パターン> <ファイル名>...");
      System.exit(1);
    }

    String patternString = args[0];
    String[] fileNames = new String[args.length - 1];
    System.arraycopy(args, 1, fileNames, 0, args.length - 1);

    Grep grep = new Grep(patternString, fileNames);
    grep.search();
  }
}

いいなと思ったら応援しよう!