1概要

このチュートリアルでは – 私たちは


Unix4J

やhttps://のようなJavaやサードパーティのライブラリを使って

与えられたファイルから** パターンを探す方法を学びます。 code.google.com/archive/p/grep4j/[Grep4J]


2バックグラウンド

Unixには

grep

という強力なコマンドがあります。これは““を表します。与えられたファイルのセット内でパターンまたは正規表現を検索します。

grepコマンドとともに0個以上のオプションを使用して、検索結果を充実させることができます。これについては、次のセクションで詳しく説明します。

Windowsを使用している場合は、https://code.google.com/archive/p/grep4j/wikis/WindowSupport.wiki[こちら]の投稿にあるようにbashをインストールできます。


3 Unix4Jライブラリを使った場合

まず、Unix4Jライブラリを使用してファイル内のパターンをgrepする方法を見てみましょう。

次の例では、UNIXのgrepコマンドをJavaで翻訳する方法を見ていきます。


3.1. ビルド構成


pom.xmlまたは

build.gradleに次の依存関係を追加します。

<dependency>
    <groupId>org.unix4j</groupId>
    <artifactId>unix4j-command</artifactId>
    <version>0.4</version>
</dependency>

** 3.2. Grepを使った例

**

Unixでのgrepのサンプル:

grep "NINETEEN" dictionary.txt

Javaと同等のものは次のとおりです。

@Test
public void whenGrepWithSimpleString__thenCorrect() {
    int expectedLineCount = 4;
    File file = new File("dictionary.txt");
    List<Line> lines = Unix4j.grep("NINETEEN", file).toLineList();

    assertEquals(expectedLineCount, lines.size());
}

もう1つの例は、ファイル内で逆テキスト検索を使用できる場合です。

これはUnix版のものです。

grep -v "NINETEEN" dictionary.txt

上記のコマンドのJavaバージョンは次のとおりです。

@Test
public void whenInverseGrepWithSimpleString__thenCorrect() {
    int expectedLineCount = 178687;
    File file = new File("dictionary.txt");
    List<Line> lines
      = Unix4j.grep(Grep.Options.v, "NINETEEN", file). toLineList();

    assertEquals(expectedLineCount, lines.size());
}

ファイル内のパターンを検索するために正規表現を使用する方法を見てみましょう。これは、ファイル全体で見つかったすべての正規表現パターンを数えるUnix版です。

grep -c ".** ?NINE.** ?" dictionary.txt

上記のコマンドのJavaバージョンは次のとおりです。

@Test
public void whenGrepWithRegex__thenCorrect() {
    int expectedLineCount = 151;
    File file = new File("dictionary.txt");
    String patternCount = Unix4j.grep(Grep.Options.c, ".** ?NINE.** ?", file).
                          cut(CutOption.fields, ":", 1).toStringResult();

    assertEquals(expectedLineCount, patternCount);
}


4 Grep4J

とは

次に、Grep4Jライブラリを使用して、ローカルまたはリモートのどこかにあるファイル内のパターンをgrepする方法を見てみましょう。

次の例では、UNIXのgrepコマンドをJavaで翻訳する方法を見ていきます。


4.1. ビルド構成


pom.xmlまたは

build.gradleに次の依存関係を追加します。

<dependency>
    <groupId>com.googlecode.grep4j</groupId>
    <artifactId>grep4j</artifactId>
    <version>1.8.7</version>
</dependency>

** 4.2. grepの例

**

Javaでのgrepのサンプル、つまり次のものと同等です。

grep "NINETEEN" dictionary.txt

これが、Java版のcommandです。

@Test
public void givenLocalFile__whenGrepWithSimpleString__thenCorrect() {
    int expectedLineCount = 4;
    Profile localProfile = ProfileBuilder.newBuilder().
                           name("dictionary.txt").filePath(".").
                           onLocalhost().build();
    GrepResults results
      = Grep4j.grep(Grep4j.constantExpression("NINETEEN"), localProfile);

    assertEquals(expectedLineCount, results.totalLines());
}

もう1つの例は、ファイル内で逆テキスト検索を使用できる場合です。

これはUnix版のものです。

grep -v "NINETEEN" dictionary.txt

そして、これがJavaバージョンです。

@Test
public void givenRemoteFile__whenInverseGrepWithSimpleString__thenCorrect() {
    int expectedLineCount = 178687;
    Profile remoteProfile = ProfileBuilder.newBuilder().
                            name("dictionary.txt").filePath(".").
                            filePath("/tmp/dictionary.txt").
                            onRemotehost("172.168.192.1").
                            credentials("user", "pass").build();
    GrepResults results = Grep4j.grep(
      Grep4j.constantExpression("NINETEEN"), remoteProfile, Option.invertMatch());

    assertEquals(expectedLineCount, results.totalLines());
}

ファイル内のパターンを検索するために正規表現を使用する方法を見てみましょう。これは、ファイル全体で見つかったすべての正規表現パターンを数えるUnix版です。

grep -c ".** ?NINE.** ?" dictionary.txt

これがJavaのバージョンです。

@Test
public void givenLocalFile__whenGrepWithRegex__thenCorrect() {
    int expectedLineCount = 151;
    Profile localProfile = ProfileBuilder.newBuilder().
                           name("dictionary.txt").filePath(".").
                           onLocalhost().build();
    GrepResults results = Grep4j.grep(
      Grep4j.regularExpression(".** ?NINE.** ?"), localProfile, Option.countMatches());

    assertEquals(expectedLineCount, results.totalLines());
}


5結論

このクイックチュートリアルでは、

Grep4j



Unix4J

を使用して特定のファイル内のパターンを検索する方法を示しました。

これらの例の実装はhttps://github.com/eugenp/tutorials/tree/master/core-java[GitHubプロジェクト]にあります – これはMavenベースのプロジェクトなので、インポートおよび実行が簡単なはずです。そのまま。

最後に、当然のことながら、JDKの

regex機能

を使用して、grepのような機能の基本の一部を実行できます。