LinuxでGrepと正規表現を使用してテキストパターンを検索する

提供:Dev Guides
移動先:案内検索

序章

grepコマンドは、Linuxターミナル環境で最も役立つコマンドの1つです。 grepという名前は、「グローバル正規表現印刷」の略です。 これは、grepを使用して、受信した入力が指定されたパターンと一致するかどうかを確認できることを意味します。 この一見些細なプログラムは非常に強力です。 複雑なルールに基づいて入力をソートする機能により、多くのコマンドチェーンで人気のあるリンクになっています。

このチュートリアルでは、grepコマンドのオプションについて説明し、次に正規表現を使用してより高度な検索を実行します。

前提条件

このガイドに従うには、Linuxベースのオペレーティングシステムを実行しているコンピューターにアクセスする必要があります。 これは、SSHで接続した仮想プライベートサーバーまたはローカルマシンのいずれかです。 このチュートリアルは、Ubuntu 20.04を実行しているLinuxサーバーを使用して検証されていますが、示されている例は、任意のバージョンのLinuxディストリビューションを実行しているコンピューターで機能するはずです。

このガイドに従うためにリモートサーバーを使用する場合は、最初に初期サーバーセットアップガイドを完了することをお勧めします。 そうすることで、sudo権限を持つroot 以外のユーザーや、UFWで構成されたファイアウォールなどの安全なサーバー環境がセットアップされます。これを使用してLinuxスキルを構築できます。

別の方法として、このページに埋め込まれているインタラクティブ端末を使用して、このチュートリアルのサンプルコマンドを試すことをお勧めします。 次のインタラクティブターミナルの起動!ボタンをクリックしてターミナルウィンドウを開き、Linux(Ubuntu)環境での作業を開始します。

インタラクティブターミナルを起動します!

基本的な使用法

このチュートリアルでは、grepを使用して、 GNU GeneralPublicLicenseバージョン3でさまざまな単語やフレーズを検索します。

Ubuntuシステムを使用している場合は、/usr/share/common-licensesフォルダーにファイルがあります。 ホームディレクトリにコピーします。

cp /usr/share/common-licenses/GPL-3 .

別のシステムを使用している場合は、curlコマンドを使用してコピーをダウンロードします。

curl -o GPL-3 https://www.gnu.org/licenses/gpl-3.0.txt

このチュートリアルでは、BSDライセンスファイルも使用します。 Linuxでは、次のコマンドを使用して、これをホームディレクトリにコピーできます。

cp /usr/share/common-licenses/BSD .

別のシステムを使用している場合は、次のコマンドを使用してファイルを作成します。

cat << 'EOF' > BSD
Copyright (c) The Regents of the University of California.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.
3. Neither the name of the University nor the names of its contributors
   may be used to endorse or promote products derived from this software
   without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
EOF

ファイルができたので、grepでの作業を開始できます。

最も基本的な形式では、grepを使用して、テキストファイル内のリテラルパターンを照合します。 これは、検索する単語をgrepに渡すと、その単語を含むファイルのすべての行が出力されることを意味します。

次のコマンドを実行してgrepを使用し、GNUという単語を含むすべての行を検索します。

grep "GNU" GPL-3

最初の引数GNUは検索するパターンであり、2番目の引数GPL-3は検索する入力ファイルです。

結果の出力は、パターンテキストを含むすべての行になります。

Output                    GNU GENERAL PUBLIC LICENSE
  The GNU General Public License is a free, copyleft license for
the GNU General Public License is intended to guarantee your freedom to
GNU General Public License for most of our software; it applies also to
  Developers that use the GNU GPL protect your rights with two steps:
  "This License" refers to version 3 of the GNU General Public License.
  13. Use with the GNU Affero General Public License.
under version 3 of the GNU Affero General Public License into a single
...
...

一部のシステムでは、検索したパターンが出力で強調表示されます。

一般的なオプション

デフォルトでは、grepは入力ファイル内で正確に指定されたパターンを検索し、見つかった行を返します。 grepにいくつかのオプションのフラグを追加することで、この動作をより便利にすることができます。

grepで検索パラメーターの「大文字と小文字」を無視し、大文字と小文字の両方のバリエーションを検索する場合は、-iまたは--ignore-caseオプションを指定できます。

次のコマンドを使用して、以前と同じファイルで単語licenseの各インスタンス(大文字、小文字、または大文字と小文字が混在)を検索します。

grep -i "license" GPL-3

結果には、LICENSElicense、およびLicenseが含まれます。

Output                    GNU GENERAL PUBLIC LICENSE
 of this license document, but changing it is not allowed.
  The GNU General Public License is a free, copyleft license for
  The licenses for most software and other practical works are designed
the GNU General Public License is intended to guarantee your freedom to
GNU General Public License for most of our software; it applies also to
price.  Our General Public Licenses are designed to make sure that you
(1) assert copyright on the software, and (2) offer you this License
  "This License" refers to version 3 of the GNU General Public License.
  "The Program" refers to any copyrightable work licensed under this
...
...

LiCeNsEのインスタンスがあった場合、それも返されます。

に指定されたパターンが含まれていないすべての行を検索する場合は、-vまたは--invert-matchオプションを使用できます。

次のコマンドを使用して、BSDライセンスでtheという単語を含まないすべての行を検索します。

grep -v "the" BSD

次の出力が表示されます。

OutputAll rights reserved.

Redistribution and use in source and binary forms, with or without
are met:
    may be used to endorse or promote products derived from this software
    without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
...
...

「大文字と小文字を区別しない」オプションを指定しなかったため、最後の2つの項目にはtheという単語がないものとして返されました。

一致が発生する行番号を知っておくと便利なことがよくあります。 これを行うには、-nまたは--line-numberオプションを使用します。 このフラグを追加して、前の例を再実行します。

grep -vn "the" BSD

これにより、次のテキストが返されます。

Output2:All rights reserved.
3:
4:Redistribution and use in source and binary forms, with or without
6:are met:
13:   may be used to endorse or promote products derived from this software
14:   without specific prior written permission.
15:
16:THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
17:ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
...
...

theを含まないすべての行に変更を加える場合は、行番号を参照できるようになりました。 これは、ソースコードを操作するときに特に便利です。

正規表現

はじめに、grepは「グローバル正規表現印刷」の略であることを学びました。 「正規表現」は、特定の検索パターンを説明するテキスト文字列です。

アプリケーションやプログラミング言語が異なれば、正規表現の実装も少し異なります。 このチュートリアルでは、grepがそのパターンを記述する方法の小さなサブセットのみを調査します。

文字通りの一致

このチュートリアルの前の例では、GNUおよびtheという単語を検索したときに、実際には文字列GNUおよびthe。 一致する文字を正確に指定するパターンは、文字通り、文字ごとにパターンと一致するため、「リテラル」と呼ばれます。

これらは、単語と一致するのではなく、文字列と一致すると考えると便利です。 より複雑なパターンを学ぶにつれて、これはより重要な区別になります。

すべてのアルファベット文字と数字文字(および特定の他の文字)は、他の式メカニズムによって変更されない限り、文字通り一致します。

アンカーマッチ

アンカーは、行のどこで一致が有効である必要があるかを指定する特殊文字です。

たとえば、アンカーを使用して、行の先頭でGNUに一致する行についてのみ知りたいことを指定できます。 これを行うには、リテラル文字列の前に^アンカーを使用できます。

次のコマンドを実行してGPL-3ファイルを検索し、GNUが行の先頭にある行を見つけます。

grep "^GNU" GPL-3

このコマンドは、次の2行を返します。

OutputGNU General Public License for most of our software; it applies also to
GNU General Public License, you may choose any version ever published

同様に、パターンの最後で$アンカーを使用して、一致が行の最後で発生した場合にのみ有効であることを示します。

このコマンドは、GPL-3ファイルのandという単語で終わるすべての行に一致します。

grep "and$" GPL-3

次の出力が表示されます。

Outputthat there is no warranty for this free software.  For both users' and
  The precise terms and conditions for copying, distribution and
  License.  Each licensee is addressed as "you".  "Licensees" and
receive it, in any medium, provided that you conspicuously and
    alternative is allowed only occasionally and noncommercially, and
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
provisionally, unless and until the copyright holder explicitly and
receives a license from the original licensors, to run, modify and
make, use, sell, offer for sale, import and otherwise run, modify and

任意の文字に一致

ピリオド文字(。)は、正規表現で使用され、指定された場所に任意の1文字が存在できることを意味します。

たとえば、GPL-3ファイル内の2文字で、次に文字列ceptを含むものと一致させるには、次のパターンを使用します。

grep "..cept" GPL-3

このコマンドは、次の出力を返します。

Outputuse, which is precisely where it is most unacceptable.  Therefore, we
infringement under applicable copyright law, except executing it on a
tells the user that there is no warranty for the work (except to the
License by making exceptions from one or more of its conditions.
form of a separately written license, or stated as exceptions;
  You may not propagate or modify a covered work except as expressly
  9. Acceptance Not Required for Having Copies.
...
...

この出力には、acceptexceptの両方のインスタンスと、2つの単語のバリエーションが含まれています。 それも見つかった場合、パターンはz2ceptとも一致します。

角かっこ式

文字のグループを角かっこ(\[および\])内に配置することにより、その位置の文字を角かっこグループ内で見つかった任意の1文字にすることができます。

たとえば、tooまたはtwoを含む行を見つけるには、次のパターンを使用してこれらのバリエーションを簡潔に指定します。

grep "t[wo]o" GPL-3

出力は、両方のバリエーションがファイルに存在することを示しています。

Outputyour programs, too.
freedoms that you received.  You must make sure that they, too, receive
  Developers that use the GNU GPL protect your rights with two steps:
a computer network, with no transfer of a copy, is not conveying.
System Libraries, or general-purpose tools or generally available free
    Corresponding Source from a network server at no charge.
...
...

角かっこ表記は、いくつかの興味深いオプションを提供します。 角かっこ内の文字のリストを^文字で始めることにより、角かっこ内の文字を除くすべてのにパターンを一致させることができます。

この例は、パターン.odeに似ていますが、パターンcodeとは一致しません。

grep "[^c]ode" GPL-3

受け取る出力は次のとおりです。

Output  1. Source Code.
    model, to give anyone who possesses the object code either (1) a
the only significant mode of use of the product.
notice like this when it starts in an interactive mode:

返された2行目には、実際にはcodeという単語があることに注意してください。 これは、正規表現またはgrepの失敗ではありません。 むしろ、この行が返されたのは、行の前半で、単語model内にあるパターンmodeが見つかったためです。 パターンに一致するインスタンスがあったため、行が返されました。

角かっこのもう1つの便利な機能は、使用可能なすべての文字を個別に入力する代わりに、文字の範囲を指定できることです。

つまり、大文字で始まるすべての行を検索する場合は、次のパターンを使用できます。

grep "^[A-Z]" GPL-3

この式が返す出力は次のとおりです。

OutputGNU General Public License for most of our software; it applies also to
States should not allow patents to restrict development and use of
License.  Each licensee is addressed as "you".  "Licensees" and
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
System Libraries, or general-purpose tools or generally available free
Source.
User Product is transferred to the recipient in perpetuity or for a
...
...

いくつかのレガシーソートの問題により、多くの場合、今使用したような文字範囲の代わりにPOSIX文字クラスを使用する方が正確です。

すべてのPOSIX文字クラスについて説明することはこのガイドの範囲を超えますが、前の例と同じ手順を実行する例では、ブラケットセレクター内で\[:upper:\]文字クラスを使用します。

grep "^[[:upper:]]" GPL-3

出力は以前と同じになります。

パターンを0回以上繰り返す

最後に、最も一般的に使用されるメタ文字の1つは、アスタリスク、つまり*です。これは、「前の文字または式を0回以上繰り返す」ことを意味します。

GPL-3ファイルで、開き括弧と閉じ括弧を含み、間に文字と1つのスペースだけがある各行を検索するには、次の式を使用します。

grep "([A-Za-z ]*)" GPL-3

次の出力が得られます。

Output Copyright (C) 2007 Free Software Foundation, Inc.
distribution (with or without modification), making available to the
than the work as a whole, that (a) is included in the normal form of
Component, and (b) serves only to enable use of the work with that
(if any) on which the executable work runs, or a compiler used to
    (including a physical distribution medium), accompanied by the
    (including a physical distribution medium), accompanied by a
    place (gratis or for a charge), and offer equivalent access to the
...
...

これまで、表現でピリオド、アスタリスク、およびその他の文字を使用してきましたが、これらの文字を具体的に検索する必要がある場合があります。

メタキャラクターの脱出

特にソースコードや構成ファイルを操作する場合は、リテラルのピリオドまたはリテラルの開き角かっこを検索する必要がある場合があります。 これらの文字は正規表現で特別な意味を持つため、この場合は特別な意味を使用したくないことをgrepに伝えるためにこれらの文字を「エスケープ」する必要があります。

通常は特別な意味を持つ文字の前に円記号(\)を使用して、文字をエスケープします。

たとえば、大文字で始まりピリオドで終わる行を見つけるには、通常の「任意の文字」の意味ではなく、リテラルピリオドを表すように、終了ピリオドをエスケープする次の式を使用します。

grep "^[A-Z].*\.$" GPL-3

これが表示される出力です。

OutputSource.
License by making exceptions from one or more of its conditions.
License would be to refrain entirely from conveying the Program.
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
SUCH DAMAGES.
Also add information on how to contact you by electronic and paper mail.

次に、他の正規表現オプションを見てみましょう。

拡張正規表現

grepコマンドは、-Eフラグを使用するか、grepの代わりにegrepコマンドを呼び出すことにより、より広範な正規表現言語をサポートします。

これらのオプションは、「拡張正規表現」の機能を開きます。 拡張正規表現には、より複雑な一致を表現するための追加のメタ文字に加えて、すべての基本的なメタ文字が含まれます。

グループ化

拡張正規表現が開く最も便利な機能の1つは、式をグループ化して1つのユニットとして操作または参照する機能です。

式をグループ化するには、それらを括弧で囲みます。 拡張正規表現を使用せずに括弧を使用する場合は、バックスラッシュを使用して括弧をエスケープし、この機能を有効にすることができます。 これは、次の3つの式が機能的に同等であることを意味します。

grep "\(grouping\)" file.txt
grep -E "(grouping)" file.txt
egrep "(grouping)" file.txt

交替

角かっこ式が単一文字の一致に対して可能なさまざまな選択肢を指定する方法と同様に、交互に使用すると、文字列または式セットの代替一致を指定できます。

交互を示すには、パイプ文字|を使用します。 これらは、括弧で囲まれたグループ内で、2つ以上の可能性のうちの1つが一致と見なされることを指定するためによく使用されます。

以下では、テキスト内にGPLまたはGeneral Public Licenseのいずれかが含まれています。

grep -E "(GPL|General Public License)" GPL-3

出力は次のようになります。

Output  The GNU General Public License is a free, copyleft license for
the GNU General Public License is intended to guarantee your freedom to
GNU General Public License for most of our software; it applies also to
price.  Our General Public Licenses are designed to make sure that you
  Developers that use the GNU GPL protect your rights with two steps:
  For the developers' and authors' protection, the GPL clearly explains
authors' sake, the GPL requires that modified versions be marked as
have designed this version of the GPL to prohibit the practice for those
...
...

交互に、追加のパイプ(|)文字で区切られた選択グループ内に追加の選択肢を追加することにより、3つ以上の選択肢から選択できます。

量指定子

前の文字または文字セットに0回以上一致した*メタ文字のように、出現回数を指定する拡張正規表現で使用可能な他のメタ文字があります。

文字を0回または1回一致させるには、?文字を使用できます。 これにより、本質的に、以前の1つまたは複数の文字セットがオプションになります。

以下は、copyをオプションのグループに入れることにより、copyrightおよびrightと一致します。

grep -E "(copy)?right" GPL-3

次の出力が表示されます。

Output Copyright (C) 2007 Free Software Foundation, Inc.
  To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights.  Therefore, you have
know their rights.
  Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
  "Copyright" also means copyright-like laws that apply to other kinds of
...

+文字は、式に1回以上一致します。 これは*メタ文字とほとんど同じですが、+文字では、式は少なくとも1回は一致する必要があります

次の式は、文字列freeに加えて、空白文字ではない1つ以上の文字と一致します。

grep -E "free[^[:space:]]+" GPL-3

次の出力が表示されます。

Output  The GNU General Public License is a free, copyleft license for
to take away your freedom to share and change the works.  By contrast,
the GNU General Public License is intended to guarantee your freedom to
  When we speak of free software, we are referring to freedom, not
have the freedom to distribute copies of free software (and charge for
you modify it: responsibilities to respect the freedom of others.
freedomss that you received.  You must make sure that they, too, receive
protecting users' freedom to change the software.  The systematic
of the GPL, as needed to protect the freedom of users.
patents cannot be used to render the program non-free.

一致の繰り返しの指定

一致が繰り返される回数を指定するには、中括弧文字({および})を使用します。 これらの文字を使用すると、式が一致できる回数の正確な数、範囲、または上限または下限を指定できます。

次の式を使用して、GPL-3ファイル内の三重母音を含むすべての行を検索します。

grep -E "[AEIOUaeiou]{3}" GPL-3

返される各行には、3つの母音を持つ単語があります。

Outputchanged, so that their problems will not be attributed erroneously to
authors of previous versions.
receive it, in any medium, provided that you conspicuously and
give under the previous paragraph, plus a right to possession of the
covered work so as to satisfy simultaneously your obligations under this

16〜20文字の単語を照合するには、次の式を使用します。

grep -E "[[:alpha:]]{16,20}" GPL-3

このコマンドの出力は次のとおりです。

Output    certain responsibilities if you distribute copies of the software, or if
    you modify it: responsibilities to respect the freedom of others.
        c) Prohibiting misrepresentation of the origin of that material, or

その長さの単語を含む行のみが表示されます。

結論

grepは、ファイル内またはファイルシステム階層内のパターンを見つけるのに役立ちます。そのため、オプションと構文に慣れるために時間を費やす価値があります。

正規表現はさらに用途が広く、多くの人気のあるプログラムで使用できます。 たとえば、多くのテキストエディタは、テキストを検索および置換するための正規表現を実装しています。

さらに、最新のプログラミング言語のほとんどは、正規表現を使用して特定のデータに対してプロシージャを実行します。 正規表現を理解すると、テキストエディタでの高度な検索の実行からユーザー入力の検証まで、その知識を多くの一般的なコンピュータ関連のタスクに転送できるようになります。