序章

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

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

前提条件

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

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

基本的な使用法

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

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

結果は次のとおりです。 LICENSE, license、 と 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 オプション。

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

  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 そのパターンを説明します。

文字通りの一致

このチュートリアルの前の例では、単語を検索したとき GNUthe、文字列と完全に一致する基本的な正規表現を実際に検索していました GNUthe. 一致する文字を正確に指定するパターンは、文字通り、文字ごとにパターンと一致するため、「リテラル」と呼ばれます。

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

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

アンカーマッチ

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

たとえば、アンカーを使用して、一致する行についてのみ知りたいことを指定できます 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

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

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

  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

任意の文字に一致

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

たとえば、 GPL-3 2文字のファイルとその後の文字列 cept、次のパターンを使用します。

  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の失敗ではありません。 むしろ、この行は、行の前半のパターンであるために返されました。 mode、単語内にあります model、 発見された。 パターンに一致するインスタンスがあったため、行が返されました。

角かっこのもう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つのスペースしかないファイルでは、次の式を使用します。

  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.

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

拡張正規表現

The grep コマンドは、を使用して、より広範な正規表現言語をサポートします -E フラグを立てるか、 egrep 代わりにコマンド grep.

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

グループ化

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

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

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

交替

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

交互を示すには、パイプ文字を使用します |. これらは、括弧で囲まれたグループ内で、2つ以上の可能性のうちの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 ... ...

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

量指定子

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

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

次の試合 copyrightright 置くことによって copy オプションのグループ:

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

The + 文字が式に1回以上一致します。 これはほとんど * メタ文字ですが、 + 文字の場合、式mustは少なくとも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

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

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

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