본문 바로가기
IT개발/Linux

[유닉스/리눅스] grep 명령어 학습

by Thompson 2024. 5. 27.
728x90

 $ grep [옵션] 패턴 파일*

파일(들)을 대상으로 지정된 패턴의 문자열을 검색하고, 해당 문자열을 포함하는
줄들을 출력합니다.

 

 

grep 명령어 사용법 및 옵션
  • 리눅스에서 grep 명령어는 파일 내에서 특정 패턴을 검색하는 데 사용됩니다. 여러 가지 옵션을 제공하여 검색 결과를 더욱 세밀하게 조정할 수 있습니다. 

 

기본 사용법
$ grep journey poem.txt
The journey of a thousand miles begins with one step. Enjoy the journey and try to get better every day. It's the journey that matters, not the destination.
$ grep -w journey poem.txt
Enjoy the journey and try to get better every day. It's the journey that matters, not the destination.
$ grep -n journey poem.txt
3:The journey of a thousand miles begins with one step.
7:Enjoy the journey and try to get better every day.
12:It's the journey that matters, not the destination.
grep 명령어의 옵션
-i 대소문자를 무시하고 검색한다.
-l 해당 패턴이 들어있는 파일 이름을 출력한다.
-n 각 줄의 줄 번호도 함께 출력한다.
-v 명시된 패턴을 포함하지 않는 줄을 출력한다.
-c 패턴과 일치하는 줄 수를 출력한다.
-w 패턴이 하나의 단어로 된 것만 검색한다.
$ grep -i nature poem.txt
Nature does not hurry, yet everything is accomplished. To walk in nature is to witness a thousand miracles. In every walk with nature, one receives far more than he seeks. Nature always wears the colors of the spirit.
$ grep -v change poem.txt
The journey of a thousand miles begins with one step. Enjoy the journey and try to get better every day. It's the journey that matters, not the destination. Nature does not hurry, yet everything is accomplished. To walk in nature is to witness a thousand miracles. In every walk with nature, one receives far more than he seeks. Nature always wears the colors of the spirit.
정규식과 파이프와 함께하는 grep 명령어 사용법

리눅스에서 grep 명령어는 파일 내에서 특정 패턴을 검색하는 데 사용됩니다. 정규식을 사용하여 더욱 복잡한 패턴을 검색할 수 있으며, 파이프를 사용하여 다른 명령어의 출력에서 패턴을 찾을 수 있습니다.

정규식 문법
. 임의의 한 문자를 의미합니다. a...b는 a로 시작해서 b로 끝나는 5글자 문자열을 찾습니다.
* 바로 앞의 것을 0번 이상의 반복을 의미합니다. a*b는 b, ab, aab, aaab, ... 등의 문자열을 찾습니다.
[ ] 대괄호 안의 문자 중 하나를 의미합니다. [abc]d는 ad, bd, cd를 뜻합니다.
- 문자의 범위를 지정합니다. [a-z]는 a부터 z까지 중 하나를 뜻합니다.
[^] 대괄호 안의 문자를 제외한 나머지 문자 중 하나를 의미합니다. [^abc]d는 ad, bd, cd를 제외한 ed, fd 등을 포함합니다.
^ 줄의 시작을 의미합니다. ^문자열은 문자열로 시작하는 줄을 나타냅니다.
$ 줄의 끝을 의미합니다. 문자열$은 문자열로 끝나는 줄을 나타냅니다.

 

기본 사용법
$ grep 'st..' you.txt
Start each day with a positive thought. Standing tall against all odds. Stop and take a deep breath. Strong winds and heavy rains. Each step you take is progress.
$ grep 'st.*e' you.txt
Start each day with a positive thought. Standing tall against all odds. Stop and take a deep breath. Strong winds and heavy rains. Each step you take is progress.
$ grep -w 'st.*e' you.txt
Start each day with a positive thought.
파이프와 함께 grep 사용하기

 

파이프(|)를 사용하여 다른 명령어의 출력에서 특정 단어 또는 문자열 패턴을 찾을 수 있습니다.

 

기본 사용법
$ ls -l | grep chang
$ ps -ef | grep chang