리눅스 명령어 grep

김규연·2023년 7월 25일
0

linux

목록 보기
11/11

⚙️ 리눅스 명령 구조

형식 -> 명령 [옵션][인자]

  • 명령 : 사용자가 컴퓨터 운영체제나 응용프로그램에게 어떤 서비스를 수행하도록 요구하는 것
  • 옵션 : 옵션을 사용하여 명령의 세부 기능을 선택할 수 있다. 리눅스의 기능을 풍부하게 하는 중요한 특징. "-"기호로 시작하며 영문 소문자나 대문자로 구성. 명령에 따라 어떤 옵션이 있고 그 기능이 무엇인지는 해당 명령의 사용법을 참조
  • 인자 : 명령으로 전달되는 값으로 주로 파일명이나 디렉터리명

🧐 문자열 찾는 명령어 grep

- grep [옵션][패턴][파일명]
리눅스에서 grep 명령어는 입력으로 전달된 파일의 내용에서 특정 문자열을 찾고자할 때 사용하는 명령어이다. 하지만 grep 명령어가 단순히 문자열이 일치하는지 여부만을 검사하는 것은 아니라 문자열이 같은지만 정규 표현식에 의한 패턴 매칭 방식을 사용하여 검사하는 수준을 넘어 훨씬 복잠하고 다양한 방식으로 매우 효율적으로 문자열을 찾는 기능을 제공한다. 다른 명령어와 조합하여 응용되는 경우가 많아서 이 grep명령어는 리눅스에서 능숙하게 사용할 줄 알아야 하는 기본 명령어이다.

📌 grep 명령어 옵션

옵션설명
-EPATTERN을 확장 정규 표현식으로 해석
-FPATTERN을 정규 표현식이 아닌 일반 문자열로 해석
-GPATTERN을 기본 정규 표현식으로 해석
-PPATTERN을 Perl 정규 표현식으로 해석
-e매칭을 위한 PATTERN 전달
-f파일에 기록된 내용을 PATTERN으로 사용
-i대/소문자 무시
-v매칭되는 PATTERN이 존재하지 않는 라인 선택
-w단어 단위로 매칭
-x라인 단위로 매칭
-z라인을 newline(\n)이 아닌 null(\0)로 구분
-m최대 검색 결과 갯수 제한
-b패턴이 매치된 각 라인(-o 사용 시 문자열)의 바이트 옵셋 출력
-n검색 결과 출력 라인 앞에 라인 번호 출력
-H검색 결과 출력 라인 앞에 파일 이름 표시
-h검색 결과 출력 시, 파일 이름 무시
-o매치되는 문자열만 표시
-q검색 결과 출력하지 않음
-a바이너리 파일을 텍스트 파일처럼 처리
-d디렉토리 처리 방식 지정
-D장치 파일 처리 방식 지정
-r하위 디렉토리 탐색
-R심볼릭 링크를 따라가며 모든 하위 디렉토리 탐색
-LPATTERN이 존재하지 않는 파일 이름만 표시
-l패턴이 존재하는 파일 이름만 표시
-c파일 당 패턴이 일치하는 라인의 갯수 출력

📌 grep의 종류

grep은 3가지 종류가 있다. egrep은 정규 표현식만으로 검색하는 것이고, fgrep은 문자열로 검색하는 grep을 말하며 각각 -E, -F 옵션을 사용했을 댸와 결과는 같다.

명령어설명정규표현식 사용
grep다중 패턴을 검색o
egrep정규 표현식 패턴으로 검색o
fgrep문자열 패턴으로 검색x

📚 실습 및 활용

📝 grep "문자열" [파일명]

파일에서 "문자열"에 해당하는 문자열을 검색한다. 대소문자를 구분해 주어야 한다. 문자열 검색 결과는 문자열을 포한한 라인 단위로 출력된다.

[root@localhost home]# grep "Hello" hello.txt
Hello World

📝 grep "문자열" *

와일드 카드 을 이용해 현재 경로에 있는 모든 파일에서 문자열을 검색할 수 있다. 뒤에 확장자를 붙여(grep "문자열" *.txt) 현재 경로에 있는 특정 확장자를 가진 모든 파일에서 문자열을 검색 할 수 있다.

[root@localhost home]# grep "Hello" *
fruit.txt:Hello World
hello.txt:Hello World
text.txt:Hello my name is Kim
text.txt:Hello my name is Kim
text.txt:Hello my name is Kim
text.txt:Hello my name is Kim
text.txt:Hello my name is Kim
text.txt:Hello my name is Kim
text.txt:Hello my name is Kim
grep: varcopy: 디렉터리입니다

📝 grep -i "문자열" [파일명]

파일에서 대/소문자를 구분하지 않고 텍스트 형식으로 문자열을 검색한다.

[root@localhost home]# grep -i "hello" text.txt
Hello my name is Kim
Hello my name is Kim
Hello my name is Kim
Hello my name is Kim
Hello my name is Kim
Hello my name is Kim
Hello my name is Kim

📝 grep -v "문자열" [파일명]

특정 문자열/패턴이 존재하지 않는 라인을 검색할 수 있다.

[root@localhost home]# cat text.txt
This is elephant
This is cat
This is banana
Hello World
Welcome
My name is Kim
My name is Lee
My name is Park
[root@localhost home]# grep -v "Hello" text.txt
This is elephant
This is cat
This is banana
Welcome
My name is Kim
My name is Lee
My name is Park

📝 grep -w "문자열" [파일명]

문자열을 단어 단위로 검색할 수 있다.

[root@localhost home]# grep -w "name" text.txt
My name is Kim
My name is Lee
My name is Park

📝 grep -n "문자열" [파일명]

파일에서 문자열이 검색된 라인번호를 포함하여 표시할 수 있다.

[root@localhost home]# grep -n "name" text.txt
6:My name is Kim
7:My name is Lee
8:My name is Park

📝 grep -H "문자열" *

파일에서 문자열이 검색된 파일명을 함께 표시할 수 있다. 와일드 카드 * 를 이용해서 여러 파일을 대상으로 검색할 경우 유용하다. (다중 파일 검색 시 따로 명시하지 않아도 기본 적용)

[root@localhost home]# grep -H "Hello" *
fruit.txt:Hello World
hello.txt:Hello World
text.txt:Hello World
grep: varcopy: 디렉터리입니다

📝 grep -r "문자열" *

현재 경로의 하위에 모든파일에 대하여 문자열을 검색할 수 있다.

[root@localhost home]# grep -r "Hello" *
fruit.txt:Hello World
hello.txt:Hello World
text.txt:Hello World
Binary file varcopy/lib/rpm/Packages matches

📝 grep -m [숫자] "문자열" *

검색 결과 개수를 제한 할 수 있다. (여러 파일을 대상으로 검색할 경우 한 파일당 개수 제한이 적용된다)

[root@localhost home]# grep -m 10 "Hello" *
fruit.txt:Hello World
hello.txt:Hello World
hello.txt:Hello World
hello.txt:Hello World
hello.txt:Hello World
hello.txt:Hello World
hello.txt:Hello World
hello.txt:Hello World
hello.txt:Hello World
hello.txt:Hello World
hello.txt:Hello World
text.txt:Hello World
grep: varcopy: 디렉터리입니다

📝 grep "A.*B" [파일명]

파일에서 A로 시작하여 B로 끝나는 패턴을 검색해 표시한다.

[root@localhost home]# grep "This.*a" text.txt
This is elephant
This is cat
This is banana

위에선 표시되지 않았지만 리눅스 화면에서 보면 빨간색 글씨로 표시된다.

📝 grep "문자열[a-z]" [파일명]

파일에서 문자열a ~ 문자열z까지의 변화되는 문자열 패턴을 검색한다.

[root@localhost home]# cat number.txt
This is number01
This is number02
This is number03
This is number04
This is number05
This is number06
This is number07
Hello World
[root@localhost home]grep "number0[1-9]" number.txt
This is number01
This is number02
This is number03
This is number04
This is number05
This is number06
This is number07

📝 grep "\." [파일명] or grep -F "." [파일명]

문자열 패턴에서 정규 표현식 메타 문자 앞에 "\"(백슬래시)를 사용하면 해당 문자를 일반 문자로 인식하게 만들 수 있다.

[root@localhost home]# cat dot.txt
Hello World.
Welcome.
My name is Kim?
*I have to do something.
[root@localhost home]# grep "\." dot.txt
Hello World.
Welcome.
*I have to do something.

📝 grep "^문자열" [파일명]

파일에서 해당하는 문자열로 시작하는 라인을 검색한다.

[root@localhost home]# grep "^This" text.txt
This is elephant
This is cat
This is banana

📝 grep "문자열$" [파일명]

파일에서 해당하는 문자열로 끝나는 라인을 검색한다.

[root@localhost home]# grep "05$" number.txt
This is number05

참고한 사이트
참고한 사이트

profile
오늘도 뚠뚠 개미 개발자

0개의 댓글