웹사이트 검색

Grep 및 정규식을 사용하여 Linux에서 텍스트 패턴 검색


소개

grep 명령은 Linux 터미널 환경에서 가장 유용한 명령 중 하나입니다. grep이라는 이름은 "global regular expression print\를 나타냅니다. 즉, grep을 사용하여 수신한 입력이 지정된 패턴과 일치하는지 확인할 수 있습니다. 이 사소해 보이는 프로그램은 매우 강력하며 복잡한 규칙에 따라 입력을 정렬하는 기능으로 인해 많은 명령 체인에서 널리 사용되는 링크입니다.

이 자습서에서는 grep 명령의 옵션을 탐색한 다음 정규식을 사용하여 고급 검색을 수행하는 방법을 알아봅니다.

전제 조건

이 가이드를 따라 하려면 Linux 기반 운영 체제를 실행하는 컴퓨터에 액세스해야 합니다. 이것은 SSH 또는 로컬 시스템으로 연결한 가상 사설 서버일 수 있습니다. 이 튜토리얼은 Ubuntu 20.04를 실행하는 Linux 서버를 사용하여 검증되었지만 주어진 예제는 모든 Linux 배포 버전을 실행하는 컴퓨터에서 작동해야 합니다.

이 가이드를 따르기 위해 원격 서버를 사용할 계획이라면 먼저 초기 서버 설정 가이드를 완료하는 것이 좋습니다. 이렇게 하면 sudo 권한이 있는 루트가 아닌 사용자와 UFW로 구성된 방화벽을 포함하여 보안 서버 환경을 설정하여 Linux 기술을 구축하는 데 사용할 수 있습니다.

기본 사용법

이 자습서에서는 grep을 사용하여 GNU General Public License 버전 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는 검색하려는 패턴이고 두 번째 인수인 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이 검색 매개변수의 "case\를 무시하고 대소문자 변형을 모두 검색하도록 하려면 -i 또는 를 지정할 수 있습니다. >--대소문자 무시 옵션.

다음 명령을 사용하여 이전과 동일한 파일에서 license라는 단어의 각 인스턴스(대문자, 소문자 또는 혼합)를 검색합니다.

  1. grep -i "license" GPL-3

결과에는 LICENSE, licenseLicense가 포함됩니다.

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

"ignore case\ 옵션을 지정하지 않았기 때문에 마지막 두 항목에 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

이 명령은 다음 두 줄을 반환합니다.

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

모든 문자 일치

마침표 문자(.)는 정규식에서 사용되어 지정된 위치에 단일 문자가 존재할 수 있음을 의미합니다.

예를 들어 GPL-3 파일에서 두 개의 문자와 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의 인스턴스와 두 단어의 변형이 있습니다. 패턴도 z2cept와 일치했을 것입니다.

대괄호 표현식

대괄호(\\[\\]) 안에 문자 그룹을 배치하면 해당 위치에 있는 문자가 대괄호 그룹 내에서 발견된 하나의 문자가 될 수 있음을 지정할 수 있습니다.

예를 들어 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:

반환된 두 번째 줄에는 실제로 code라는 단어가 있습니다. 이것은 정규 표현식이나 grep의 실패가 아닙니다. 오히려 이 줄은 model이라는 단어 내에서 찾은 mode 패턴이 줄의 앞부분에서 발견되었기 때문에 반환되었습니다. 패턴과 일치하는 인스턴스가 있기 때문에 라인이 반환되었습니다.

대괄호의 또 다른 유용한 기능은 사용 가능한 모든 문자를 개별적으로 입력하는 대신 문자 범위를 지정할 수 있다는 것입니다.

즉, 대문자로 시작하는 모든 줄을 찾으려면 다음 패턴을 사용할 수 있습니다.

  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회 이상 반복

마지막으로 가장 일반적으로 사용되는 메타 문자 중 하나는 별표 또는 *로, "이전 문자 또는 표현을 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. grep "\(grouping\)" file.txt
  2. grep -E "(grouping)" file.txt
  3. egrep "(grouping)" file.txt

교대

대괄호 표현식이 단일 문자 일치에 대해 가능한 다른 선택을 지정할 수 있는 방법과 유사하게 교체를 통해 문자열 또는 표현식 세트에 대한 대체 일치를 지정할 수 있습니다.

교대를 표시하려면 파이프 문자 |를 사용하십시오. 두 개 이상의 가능성 중 하나가 일치로 간주되어야 함을 지정하기 위해 괄호 그룹 내에서 자주 사용됩니다.

다음은 텍스트에서 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 ... ...

대체는 추가 파이프(|) 문자로 구분된 선택 그룹 내에 추가 선택 항목을 추가하여 두 개 이상의 선택 항목 중에서 선택할 수 있습니다.

수량자

이전 문자 또는 문자 집합과 0번 이상 일치한 * 메타 문자와 같이 발생 횟수를 지정하는 확장 정규식에서 사용할 수 있는 다른 메타 문자가 있습니다.

문자를 0번 또는 1번 일치시키려면 ? 문자를 사용할 수 있습니다. 이것은 본질적으로 이전에 온 문자 또는 문자 세트를 선택 사항으로 만듭니다.

다음은 선택적 그룹에 copy를 넣어 copyrightright를 일치시킵니다.

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

+ 문자는 표현식과 한 번 이상 일치합니다. 이것은 * 메타 문자와 거의 비슷하지만 + 문자를 사용하면 표현식이 적어도 한 번은 일치해야 합니다.

다음 식은 문자열 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 파일에서 삼중 모음을 포함하는 모든 줄을 찾습니다.

  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은 파일 내 또는 파일 시스템 계층 내에서 패턴을 찾는 데 유용하므로 옵션과 구문에 익숙해지는 데 시간을 할애할 가치가 있습니다.

정규식은 훨씬 더 다양하며 널리 사용되는 많은 프로그램에서 사용할 수 있습니다. 예를 들어 많은 텍스트 편집기는 텍스트를 검색하고 바꾸기 위한 정규식을 구현합니다.

또한 대부분의 최신 프로그래밍 언어는 정규식을 사용하여 특정 데이터 조각에 대한 절차를 수행합니다. 정규식을 이해하고 나면 텍스트 편집기에서 고급 검색을 수행하는 것부터 사용자 입력의 유효성을 검사하는 것까지 많은 일반적인 컴퓨터 관련 작업에 해당 지식을 적용할 수 있습니다.