Linuxでテキストパターンを検索するためのGrep&正規表現の使用

はじめに

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

このチュートリアルでは、grepコマンドのオプションを探求し、その後、より高度な検索を行うために正規表現を使用します。

前提条件

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

このガイドに従ってリモートサーバーを使用する予定であれば、ますますまずInitial Server Setup guideを完了することをお勧めします。これにより、非rootユーザーにsudo特権が付与されたセキュアなサーバー環境が構築され、UFWで構成されたファイアウォールが用意されます。これにより、Linuxスキルを構築するために使用できます。

基本的な使用方法

このチュートリアルでは、GNU General Public License version 3を検索するためにgrepを使用します。さまざまな単語やフレーズ。

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

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

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

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

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

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

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

  1. cat << 'EOF' > BSD
  2. Copyright (c) The Regents of the University of California.
  3. All rights reserved.
  4. Redistribution and use in source and binary forms, with or without
  5. modification, are permitted provided that the following conditions
  6. are met:
  7. 1. Redistributions of source code must retain the above copyright
  8. notice, this list of conditions and the following disclaimer.
  9. 2. Redistributions in binary form must reproduce the above copyright
  10. notice, this list of conditions and the following disclaimer in the
  11. documentation and/or other materials provided with the distribution.
  12. 3. Neither the name of the University nor the names of its contributors
  13. may be used to endorse or promote products derived from this software
  14. without specific prior written permission.
  15. THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
  16. ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  18. ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
  19. FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  21. OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  22. HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  23. LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  24. OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  25. SUCH DAMAGE.
  26. EOF

これでファイルを手に入れたので、grepを使って作業を開始できます。

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

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

  1. 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の各インスタンスを検索するには、次のコマンドを使用します:

  1. 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を含まないすべての行を検索します:

  1. grep -v "the" BSD

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

Output
All 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オプションを使用することで実現できます。前の例をこのフラグを追加して再実行します:

  1. grep -vn "the" BSD

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

Output
2: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が出現する行を見つけます:

  1. grep "^GNU" GPL-3

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

Output
GNU 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で終わるすべての行に一致します:

  1. grep "and$" GPL-3

次の出力を受け取ります:

Output
that 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

任意の文字の一致

ピリオド文字(.)は、正規表現で指定された位置に任意の単一の文字が存在することを意味します。

たとえば、2つの文字があり、その後に文字列ceptがあるGPL-3ファイル内のすべてのものに一致するように、次のパターンを使用します:

  1. grep "..cept" GPL-3

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

Output
use, 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を含む行を見つけるには、次のパターンを使用してこれらの変化を簡潔に指定します:

  1. grep "t[wo]o" GPL-3

出力には、両方の変化がファイルに存在することが示されます:

Output
your 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パターンには一致しません:

  1. 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つの便利な機能は、個々の利用可能な文字を個別に入力する代わりに、文字の範囲を指定できることです。

つまり、大文字で始まるすべての行を見つけたい場合、次のパターンを使用できます:

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

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

Output
GNU 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:\]文字クラスを使用した例があります。

  1. 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に伝えるためにこれらの文字を「エスケープ」する必要があります。

文字をエスケープするには、通常特別な意味を持つはずの文字の前にバックスラッシュ文字(\)を使用します。

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

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

こちらが出力される内容です:

Output
Source. 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つの単位として操作または参照する能力です。

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

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

交替

ブラケット式が1文字の一致の異なる可能な選択肢を指定できるように、交替は文字列や式セットの代替一致を指定できます。

交替を示すには、パイプ文字|を使用します。これらは、1つ以上の選択肢のうちの1つを一致として考慮することを指定するために、しばしば括弧で囲まれたグループ内で使用されます。

次の例では、テキスト内のGPLまたはGeneral Public Licenseを見つけます:

  1. 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 ... ...

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

量指定子

前の文字または文字セットが0回以上マッチする*メタ文字のように、拡張正規表現で利用可能な他のメタ文字があります。

文字を0回または1回マッチさせるには、?文字を使用します。これにより、前に来た文字または文字セットがオプションになります。

次の例は、copyをオプションのグループに入れて、copyrightおよびrightをマッチさせます:

  1. 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つ以上の空白文字以外の文字がマッチします:

  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ファイルのすべての行を見つけるために、次の式を使用してください:

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

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

Output
changed, 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文字の間の単語に一致するには、次の式を使用してください:

  1. 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は、ファイルまたはファイルシステム階層内のパターンを見つけるのに役立ちますので、そのオプションと構文に慣れるのに時間を費やす価値があります。

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

さらに、ほとんどの現代のプログラミング言語は、特定のデータの手続きを実行するために正規表現を使用します。正規表現を理解すると、テキストエディタでの高度な検索からユーザー入力の検証まで、多くの一般的なコンピュータ関連のタスクにその知識を移すことができます。

Source:
https://www.digitalocean.com/community/tutorials/using-grep-regular-expressions-to-search-for-text-patterns-in-linux