리눅스 / 명령어 / grep

grep은 리눅스 운영체제에서 문자열 검색에 사용되는 명령어입니다. grep은 Global Regular Expression Print의 약자로, 텍스트 파일에서 특정 문자열이나 정규 표현식(패턴)을 검색하고, 해당 줄을 출력합니다.

기본

기본 구조는 다음과 같습니다.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
grep [옵션] '검색할 패턴' 파일명
grep [옵션] '검색할 패턴' 파일명
grep [옵션] '검색할 패턴' 파일명

예제 1

예를 들어 다음과 같은 a.txt와 b.txt가 있다고 할 때...

a.txt

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
abc bcd cde
bcd cde def
efg fgh ghi
abc bcd cde bcd cde def efg fgh ghi
abc bcd cde
bcd cde def
efg fgh ghi

b.txt

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
abc bcd cde
bcd cde def
efg fgh ghi
abc bcd cde bcd cde def efg fgh ghi
abc bcd cde
bcd cde def
efg fgh ghi
  • a.txt에서 bcd를 포함한 줄을 출력합니다.
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
# grep bcd a.txt
abc bcd cde
bcd cde def
# grep bcd a.txt abc bcd cde bcd cde def
# grep bcd a.txt
abc bcd cde
bcd cde def
  • 검색어에 공백이 있는 경우 큰 따옴표 또는 작은 따옴표로 감쌉니다.
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
# grep "abc bcd" a.txt
abc bcd cde
# grep "abc bcd" a.txt abc bcd cde
# grep "abc bcd" a.txt
abc bcd cde
  • 기본적으로 대소문자를 구분합니다. -i 옵션을 사용하면 대소문자를 구분하지 않습니다.
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
# grep -i BCD a.txt
abc bcd cde
bcd cde def
# grep -i BCD a.txt abc bcd cde bcd cde def
# grep -i BCD a.txt
abc bcd cde
bcd cde def
  • -v 옵션을 사용하면 검색어를 포함하지 않는 줄을 출력합니다.
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
# grep -v bcd a.txt
efg fgh ghi
# grep -v bcd a.txt efg fgh ghi
# grep -v bcd a.txt
efg fgh ghi
  • -n 옵션을 사용하면 줄번호를 표시합니다.
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
# grep -n bcd a.txt
1:abc bcd cde
2:bcd cde def
# grep -n bcd a.txt 1:abc bcd cde 2:bcd cde def
# grep -n bcd a.txt
1:abc bcd cde
2:bcd cde def
  • -c 옵션을 사용하면 검색어를 포함한 줄의 개수를 출력합니다.
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
# grep -c bcd a.txt
2
# grep -c bcd a.txt 2
# grep -c bcd a.txt
2
  • 파일명을 여러 개 넣으면, 해당 파일들을 대상으로 결과를 출력합니다. 결과 앞에는 파일명이 표시됩니다.
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
# grep bcd a.txt b.txt
a.txt:abc bcd cde
a.txt:bcd cde def
b.txt:abc bcd cde
b.txt:bcd cde def
# grep bcd a.txt b.txt a.txt:abc bcd cde a.txt:bcd cde def b.txt:abc bcd cde b.txt:bcd cde def
# grep bcd a.txt b.txt
a.txt:abc bcd cde
a.txt:bcd cde def
b.txt:abc bcd cde
b.txt:bcd cde def
  • 와일드카드를 이용할 수도 있습니다. 다음과 같이 하면 확장자가 txt인 모든 파일을 대상으로 검색합니다.
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
p# grep bcd *.txt
a.txt:abc bcd cde
a.txt:bcd cde def
b.txt:abc bcd cde
b.txt:bcd cde def
p# grep bcd *.txt a.txt:abc bcd cde a.txt:bcd cde def b.txt:abc bcd cde b.txt:bcd cde def
p# grep bcd *.txt
a.txt:abc bcd cde
a.txt:bcd cde def
b.txt:abc bcd cde
b.txt:bcd cde def
  • -l 옵션을 사용하면 파일명만 출력합니다.
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
# grep -l bcd *.txt
a.txt
b.txt
# grep -l bcd *.txt a.txt b.txt
# grep -l bcd *.txt
a.txt
b.txt
  • -r 옵션을 사용하고, 파일명 위치에 디렉토리 이름을 넣으면, 해당 디렉토리와 그 하위 디렉토리에 있는 모는 파일에 대하여 검색합니다.
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
# grep -r bcd ./
./a.txt:abc bcd cde
./a.txt:bcd cde def
./b.txt:abc bcd cde
./b.txt:bcd cde def
# grep -r bcd ./ ./a.txt:abc bcd cde ./a.txt:bcd cde def ./b.txt:abc bcd cde ./b.txt:bcd cde def
# grep -r bcd ./
./a.txt:abc bcd cde
./a.txt:bcd cde def
./b.txt:abc bcd cde
./b.txt:bcd cde def

예제 2

명령어로 출력되는 결과에서 검색어를 포함하는 줄을 추려낼 수 있습니다.

  • dmesg(시스템 부팅 메시지 확인 명령어)로 출력되는 결과에서 usb를 포함하는 줄을 찾습니다.
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
# dmesg | grep -i usb
[ 0.091630] ACPI: bus type USB registered
[ 0.091648] usbcore: registered new interface driver usbfs
[ 0.091657] usbcore: registered new interface driver hub
[ 0.091669] usbcore: registered new device driver usb
# dmesg | grep -i usb [ 0.091630] ACPI: bus type USB registered [ 0.091648] usbcore: registered new interface driver usbfs [ 0.091657] usbcore: registered new interface driver hub [ 0.091669] usbcore: registered new device driver usb
# dmesg | grep -i usb
[    0.091630] ACPI: bus type USB registered
[    0.091648] usbcore: registered new interface driver usbfs
[    0.091657] usbcore: registered new interface driver hub
[    0.091669] usbcore: registered new device driver usb
  • apache2 서비스 상태를 출력합니다.
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
# systemctl list-unit-files | grep apache2
apache2.service enabled enabled
apache2@.service disabled enabled
# systemctl list-unit-files | grep apache2 apache2.service enabled enabled apache2@.service disabled enabled
# systemctl list-unit-files | grep apache2
apache2.service                            enabled         enabled
apache2@.service                           disabled        enabled

도움말

도움말은 다음과 같습니다.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
# grep --help
Usage: grep [OPTION]... PATTERNS [FILE]...
Search for PATTERNS in each FILE.
Example: grep -i 'hello world' menu.h main.c
PATTERNS can contain multiple patterns separated by newlines.
Pattern selection and interpretation:
-E, --extended-regexp PATTERNS are extended regular expressions
-F, --fixed-strings PATTERNS are strings
-G, --basic-regexp PATTERNS are basic regular expressions
-P, --perl-regexp PATTERNS are Perl regular expressions
-e, --regexp=PATTERNS use PATTERNS for matching
-f, --file=FILE take PATTERNS from FILE
-i, --ignore-case ignore case distinctions in patterns and data
--no-ignore-case do not ignore case distinctions (default)
-w, --word-regexp match only whole words
-x, --line-regexp match only whole lines
-z, --null-data a data line ends in 0 byte, not newline
Miscellaneous:
-s, --no-messages suppress error messages
-v, --invert-match select non-matching lines
-V, --version display version information and exit
--help display this help text and exit
Output control:
-m, --max-count=NUM stop after NUM selected lines
-b, --byte-offset print the byte offset with output lines
-n, --line-number print line number with output lines
--line-buffered flush output on every line
-H, --with-filename print file name with output lines
-h, --no-filename suppress the file name prefix on output
--label=LABEL use LABEL as the standard input file name prefix
-o, --only-matching show only nonempty parts of lines that match
-q, --quiet, --silent suppress all normal output
--binary-files=TYPE assume that binary files are TYPE;
TYPE is 'binary', 'text', or 'without-match'
-a, --text equivalent to --binary-files=text
-I equivalent to --binary-files=without-match
-d, --directories=ACTION how to handle directories;
ACTION is 'read', 'recurse', or 'skip'
-D, --devices=ACTION how to handle devices, FIFOs and sockets;
ACTION is 'read' or 'skip'
-r, --recursive like --directories=recurse
-R, --dereference-recursive likewise, but follow all symlinks
--include=GLOB search only files that match GLOB (a file pattern)
--exclude=GLOB skip files that match GLOB
--exclude-from=FILE skip files that match any file pattern from FILE
--exclude-dir=GLOB skip directories that match GLOB
-L, --files-without-match print only names of FILEs with no selected lines
-l, --files-with-matches print only names of FILEs with selected lines
-c, --count print only a count of selected lines per FILE
-T, --initial-tab make tabs line up (if needed)
-Z, --null print 0 byte after FILE name
Context control:
-B, --before-context=NUM print NUM lines of leading context
-A, --after-context=NUM print NUM lines of trailing context
-C, --context=NUM print NUM lines of output context
-NUM same as --context=NUM
--group-separator=SEP print SEP on line between matches with context
--no-group-separator do not print separator for matches with context
--color[=WHEN],
--colour[=WHEN] use markers to highlight the matching strings;
WHEN is 'always', 'never', or 'auto'
-U, --binary do not strip CR characters at EOL (MSDOS/Windows)
When FILE is '-', read standard input. With no FILE, read '.' if
recursive, '-' otherwise. With fewer than two FILEs, assume -h.
Exit status is 0 if any line is selected, 1 otherwise;
if any error occurs and -q is not given, the exit status is 2.
Report bugs to: bug-grep@gnu.org
GNU grep home page: <https://www.gnu.org/software/grep/>
General help using GNU software: <https://www.gnu.org/gethelp/>
# grep --help Usage: grep [OPTION]... PATTERNS [FILE]... Search for PATTERNS in each FILE. Example: grep -i 'hello world' menu.h main.c PATTERNS can contain multiple patterns separated by newlines. Pattern selection and interpretation: -E, --extended-regexp PATTERNS are extended regular expressions -F, --fixed-strings PATTERNS are strings -G, --basic-regexp PATTERNS are basic regular expressions -P, --perl-regexp PATTERNS are Perl regular expressions -e, --regexp=PATTERNS use PATTERNS for matching -f, --file=FILE take PATTERNS from FILE -i, --ignore-case ignore case distinctions in patterns and data --no-ignore-case do not ignore case distinctions (default) -w, --word-regexp match only whole words -x, --line-regexp match only whole lines -z, --null-data a data line ends in 0 byte, not newline Miscellaneous: -s, --no-messages suppress error messages -v, --invert-match select non-matching lines -V, --version display version information and exit --help display this help text and exit Output control: -m, --max-count=NUM stop after NUM selected lines -b, --byte-offset print the byte offset with output lines -n, --line-number print line number with output lines --line-buffered flush output on every line -H, --with-filename print file name with output lines -h, --no-filename suppress the file name prefix on output --label=LABEL use LABEL as the standard input file name prefix -o, --only-matching show only nonempty parts of lines that match -q, --quiet, --silent suppress all normal output --binary-files=TYPE assume that binary files are TYPE; TYPE is 'binary', 'text', or 'without-match' -a, --text equivalent to --binary-files=text -I equivalent to --binary-files=without-match -d, --directories=ACTION how to handle directories; ACTION is 'read', 'recurse', or 'skip' -D, --devices=ACTION how to handle devices, FIFOs and sockets; ACTION is 'read' or 'skip' -r, --recursive like --directories=recurse -R, --dereference-recursive likewise, but follow all symlinks --include=GLOB search only files that match GLOB (a file pattern) --exclude=GLOB skip files that match GLOB --exclude-from=FILE skip files that match any file pattern from FILE --exclude-dir=GLOB skip directories that match GLOB -L, --files-without-match print only names of FILEs with no selected lines -l, --files-with-matches print only names of FILEs with selected lines -c, --count print only a count of selected lines per FILE -T, --initial-tab make tabs line up (if needed) -Z, --null print 0 byte after FILE name Context control: -B, --before-context=NUM print NUM lines of leading context -A, --after-context=NUM print NUM lines of trailing context -C, --context=NUM print NUM lines of output context -NUM same as --context=NUM --group-separator=SEP print SEP on line between matches with context --no-group-separator do not print separator for matches with context --color[=WHEN], --colour[=WHEN] use markers to highlight the matching strings; WHEN is 'always', 'never', or 'auto' -U, --binary do not strip CR characters at EOL (MSDOS/Windows) When FILE is '-', read standard input. With no FILE, read '.' if recursive, '-' otherwise. With fewer than two FILEs, assume -h. Exit status is 0 if any line is selected, 1 otherwise; if any error occurs and -q is not given, the exit status is 2. Report bugs to: bug-grep@gnu.org GNU grep home page: <https://www.gnu.org/software/grep/> General help using GNU software: <https://www.gnu.org/gethelp/>
# grep --help
Usage: grep [OPTION]... PATTERNS [FILE]...
Search for PATTERNS in each FILE.
Example: grep -i 'hello world' menu.h main.c
PATTERNS can contain multiple patterns separated by newlines.

Pattern selection and interpretation:
  -E, --extended-regexp     PATTERNS are extended regular expressions
  -F, --fixed-strings       PATTERNS are strings
  -G, --basic-regexp        PATTERNS are basic regular expressions
  -P, --perl-regexp         PATTERNS are Perl regular expressions
  -e, --regexp=PATTERNS     use PATTERNS for matching
  -f, --file=FILE           take PATTERNS from FILE
  -i, --ignore-case         ignore case distinctions in patterns and data
      --no-ignore-case      do not ignore case distinctions (default)
  -w, --word-regexp         match only whole words
  -x, --line-regexp         match only whole lines
  -z, --null-data           a data line ends in 0 byte, not newline

Miscellaneous:
  -s, --no-messages         suppress error messages
  -v, --invert-match        select non-matching lines
  -V, --version             display version information and exit
      --help                display this help text and exit

Output control:
  -m, --max-count=NUM       stop after NUM selected lines
  -b, --byte-offset         print the byte offset with output lines
  -n, --line-number         print line number with output lines
      --line-buffered       flush output on every line
  -H, --with-filename       print file name with output lines
  -h, --no-filename         suppress the file name prefix on output
      --label=LABEL         use LABEL as the standard input file name prefix
  -o, --only-matching       show only nonempty parts of lines that match
  -q, --quiet, --silent     suppress all normal output
      --binary-files=TYPE   assume that binary files are TYPE;
                            TYPE is 'binary', 'text', or 'without-match'
  -a, --text                equivalent to --binary-files=text
  -I                        equivalent to --binary-files=without-match
  -d, --directories=ACTION  how to handle directories;
                            ACTION is 'read', 'recurse', or 'skip'
  -D, --devices=ACTION      how to handle devices, FIFOs and sockets;
                            ACTION is 'read' or 'skip'
  -r, --recursive           like --directories=recurse
  -R, --dereference-recursive  likewise, but follow all symlinks
      --include=GLOB        search only files that match GLOB (a file pattern)
      --exclude=GLOB        skip files that match GLOB
      --exclude-from=FILE   skip files that match any file pattern from FILE
      --exclude-dir=GLOB    skip directories that match GLOB
  -L, --files-without-match  print only names of FILEs with no selected lines
  -l, --files-with-matches  print only names of FILEs with selected lines
  -c, --count               print only a count of selected lines per FILE
  -T, --initial-tab         make tabs line up (if needed)
  -Z, --null                print 0 byte after FILE name

Context control:
  -B, --before-context=NUM  print NUM lines of leading context
  -A, --after-context=NUM   print NUM lines of trailing context
  -C, --context=NUM         print NUM lines of output context
  -NUM                      same as --context=NUM
      --group-separator=SEP  print SEP on line between matches with context
      --no-group-separator  do not print separator for matches with context
      --color[=WHEN],
      --colour[=WHEN]       use markers to highlight the matching strings;
                            WHEN is 'always', 'never', or 'auto'
  -U, --binary              do not strip CR characters at EOL (MSDOS/Windows)

When FILE is '-', read standard input.  With no FILE, read '.' if
recursive, '-' otherwise.  With fewer than two FILEs, assume -h.
Exit status is 0 if any line is selected, 1 otherwise;
if any error occurs and -q is not given, the exit status is 2.

Report bugs to: bug-grep@gnu.org
GNU grep home page: <https://www.gnu.org/software/grep/>
General help using GNU software: <https://www.gnu.org/gethelp/>

 

같은 카테고리의 다른 글
Rocky Linux 9 / SSH / 포트 변경하는 방법

Rocky Linux 9 / SSH / 포트 변경하는 방법

SSH는 22 포트를 사용한다. 알려진 포트이므로 다른 포트로 변경하는 것이 보안상 좋다. Rocky Linux 9에서 SSH 포트 변경하는 방법은 다음과 같다. 포트를 1980으로 바꾼다고 가정한다. /etc/ssh/sshd_config에서 다음의 코드를... #Port 22 다음으로 변경한다. Port 1980 SELINUX가 활성화되어 있다면 다음과 같이 명령하여 1980 포트를 사용할 수 있게 만든다. semanage port -a -t ssh_port_t -p tcp 1980 만약 다음과 같은 ...

Ubuntu Server / 22.04 / 네트워크 세팅에 이더넷(Wired) 보이지 않을 때 해결 방법

Ubuntu Server / 22.04 / 네트워크 세팅에 이더넷(Wired) 보이지 않을 때 해결 방법

우분투 설정의 네트워크에 Wired가 보이지 않는다. 그것이 보여야 GUI로 IP 설정이 가능한데 말이다. 이를 보이게 하는 방법이 여러 가지가 있는 거 같은데, 내가 성공한 방법은... /etc/netplan/00-installer-config.yaml의 내용은 다음처럼 생겼을 것이다. # This is the network config written by 'subiquity' network: ethernets: eth0: dhcp4: true ...

리눅스 / 배포판 / 데비안(Debian) - 역사, 특징, 장점

데비안의 역사 데비안(Debian)은 자유 소프트웨어 재단의 리눅스 배포판으로 1993년에 이안 머독(Ian Murdock)에 의해 시작되었습니다. 데비안 프로젝트는 커뮤니티 기반의 오픈 소스 프로젝트로서, 전 세계의 개발자와 기여자들이 협력하여 발전시켜 왔습니다. 데비안은 GNU 프로젝트의 일환으로 시작되었으며, 현재는 리눅스 커널뿐만 아니라 다양한 커널을 지원하는 운영체제를 제공합니다. 초기 역사 1993년 8월 16일, 이안 머독은 데비안 프로젝트를 발표했습니다. 데비안의 ...

리눅스 / 캐시 메모리 삭제하는 방법

free 명령어로 메모리 사용 현황을 볼 수 있다. 아래의 경우 free에 여유가 있는데, 만약 buff/cache 사용량이 많아 free에 공간이 없다면 시스템이 느려진다. 그런 경우 메모리 캐시를 삭제하여 속도를 향상 시킬 수 있다. # free total ...

Ubuntu 24.04 Server / 고정 IP 설정하는 방법

네트워크 설정 파일은 /etc/netplan 디렉토리 안에 있는 yaml 파일입니다. 파일 이름은 시스템마다 다를 수 있습니다. # ll /etc/netplan total 12 drwxr-xr-x 2 root root 4096 Apr 27 23:00 ./ drwxr-xr-x 108 root root 4096 Apr 27 23:06 ../ -rw------- 1 root root 389 Apr 27 23:00 50-cloud-init.yaml DHCP라면 설정 파일이 다음과 ...

Rocky Linux 9 / 설치

Rocky Linux 9 / 설치

다운로드 아래 링크에서 ISO 파일을 다운로드한다. https://rockylinux.org/download Boot, Minimal, DVD 세 가지가 있는데, 다음과 같이 설명되어 있다. Boot Used to install the operating system from another source (such as a HTTP repository of the binary files). Can also be used to enter Rescue Mode. Minimal Used to install the operating system from another source (such as a ...

리눅스 / 명령어 / cd / 다른 디렉토리로 이동하는 명령어

cd는 change directory의 약자로, 다른 디렉토리로 이동하는 명령어이다. cd 현재 로그인한 사용자의 홈 디렉토리로 이동한다. 일반적으로 root 계정이라면 /root로, 사용자 jb 계정이라면 /home/jb로 이동한다. cd ~user user의 홈 디렉토리로 이동한다. 다음과 같이 명령하면 jb 사용자의 홈 디렉토리로 이동한다. # cd ~jb cd 디렉토리명 지정한 디렉토리로 이동한다. 절대경로, 상대경로 다 사용할 수 있다. 다음과 같이 명령하면 /etc 디렉토리로 이동한다. # cd /etc 현재 ...

리눅스 / 스왑 메모리(Swap Memory) 만드는 방법

리눅스 시스템이 메모리를 다 사용하면 프로그램이 멈추는 등 문제가 발생한다. 이때 스왑 메모리(Swap Memory) 늘려서 메모리 부족 문제를 해결할 수 있다. 스왑 파일 만들기 적당한 디렉토리에 적당한 이름의 파일을 적당한 크기로 만든다. 예를 들어 다음과 같이 하면, 루트 디렉토리에 jb-swap이라는 파일을 2G의 크기로 만든다. # fallocate -l 2G /jb-swap root만 읽고 쓸 수 있게 권한 ...

CentOS 7 / hostname 확인하고 변경하는 방법

CentOS 7 / hostname 확인하고 변경하는 방법

명령어 이용하기 hostname 확인 다음과 같이 명령하면 hostname을 출력한다. hostname hostname 변경 다음과 같이 명령하면 hostname을 abc로 변경한다. hostnamectl set-hostname abc 설정 파일 이용하기 hostname 확인 hostname 설정 파일은 /etc/hostname이다. 그 파일을 열거나 다음과 같이 명령하여 설정 파일의 내용을 볼 수 있다. cat /etc/hostname hostname 변경 텍스트 편집기로 열면 한 줄의 코드가 있는데, 그것이 hostname이다. 그 코드를 바꾸고 저장하면 hostname이 변경된다. 변경 사항 ...

CentOS / 설치용 부팅 USB 만드는 방법

CentOS / 설치용 부팅 USB 만드는 방법

CentOS를 설치하려면 다운로드 받은 ISO 파일을 부팅 가능한 CD 또는 USB로 만들어야 한다. ISO를 부팅 가능한 미디어로 만들어주는 프로그램은 여러 가지가 있는데, 그 중 많이 사용되는 것은 Rufus다. Rufus 다운로드 https://rufus.ie/에서 밑으로 내려가면 다운로드할 수 있는 링크가 있다. Rufus Portable은 설치가 필요 없는 실행 파일이다. 개인적으로 Portable 버전을 선호한다. CentOS 부팅 USB 만들기 Rufus를 실행한다. 다음과 ...