리눅스 / 명령어 / grep
Created 2025-05-28
Last Modified 2025-05-31
grep은 리눅스 운영체제에서 문자열 검색에 사용되는 명령어입니다. grep은 Global Regular Expression Print의 약자로, 텍스트 파일에서 특정 문자열이나 정규 표현식(패턴)을 검색하고, 해당 줄을 출력합니다.
기본
기본 구조는 다음과 같습니다.
grep [옵션] '검색할 패턴' 파일명
grep [옵션] '검색할 패턴' 파일명
grep [옵션] '검색할 패턴' 파일명
예제 1
예를 들어 다음과 같은 a.txt와 b.txt가 있다고 할 때...
a.txt
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
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를 포함한 줄을 출력합니다.
# 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
- 검색어에 공백이 있는 경우 큰 따옴표 또는 작은 따옴표로 감쌉니다.
# 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 옵션을 사용하면 대소문자를 구분하지 않습니다.
# 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 옵션을 사용하면 검색어를 포함하지 않는 줄을 출력합니다.
# 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 옵션을 사용하면 줄번호를 표시합니다.
# 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 옵션을 사용하면 검색어를 포함한 줄의 개수를 출력합니다.
# grep -c bcd a.txt
2
# grep -c bcd a.txt
2
# grep -c bcd a.txt 2
- 파일명을 여러 개 넣으면, 해당 파일들을 대상으로 결과를 출력합니다. 결과 앞에는 파일명이 표시됩니다.
# 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인 모든 파일을 대상으로 검색합니다.
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 옵션을 사용하면 파일명만 출력합니다.
# 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 옵션을 사용하고, 파일명 위치에 디렉토리 이름을 넣으면, 해당 디렉토리와 그 하위 디렉토리에 있는 모는 파일에 대하여 검색합니다.
# 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를 포함하는 줄을 찾습니다.
# 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 서비스 상태를 출력합니다.
# 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
도움말
도움말은 다음과 같습니다.
# 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/>