리눅스 / 명령어 / grep

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

기본

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

grep [옵션] '검색할 패턴' 파일명

예제 1

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

a.txt

abc bcd cde
bcd cde def
efg fgh ghi

b.txt

abc bcd cde
bcd cde def
efg fgh ghi
  • a.txt에서 bcd를 포함한 줄을 출력합니다.
# grep bcd a.txt
abc bcd cde
bcd cde def
  • 검색어에 공백이 있는 경우 큰 따옴표 또는 작은 따옴표로 감쌉니다.
# grep "abc bcd" a.txt
abc bcd cde
  • 기본적으로 대소문자를 구분합니다. -i 옵션을 사용하면 대소문자를 구분하지 않습니다.
# grep -i BCD a.txt
abc bcd cde
bcd cde def
  • -v 옵션을 사용하면 검색어를 포함하지 않는 줄을 출력합니다.
# grep -v bcd a.txt
efg fgh ghi
  • -n 옵션을 사용하면 줄번호를 표시합니다.
# grep -n bcd a.txt
1:abc bcd cde
2:bcd cde def
  • -c 옵션을 사용하면 검색어를 포함한 줄의 개수를 출력합니다.
# 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
  • 와일드카드를 이용할 수도 있습니다. 다음과 같이 하면 확장자가 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
  • -l 옵션을 사용하면 파일명만 출력합니다.
# 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

예제 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
  • apache2 서비스 상태를 출력합니다.
# 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/>

 

같은 카테고리의 다른 글
CentOS 8 / NAS의 공유 폴더 마운트하는 방법

CentOS 8 / NAS의 공유 폴더 마운트하는 방법

저장소로 또는 공유 목적으로 NAS를 사용합니다. 윈도우라면 네트워크 드라이브 연결로 NAS의 파일에 접근합니다. 리눅스라면 좀 번거로운 과정을 거칩니다. 아래는 CentOS 8에서 NAS의 공유 폴더에 접근하는 방법입니다. TUI cifs-utils 패키지를 설치합니다. dnf install cifs-utils 다음과 같이 마운트합니다. 192.168.0.101은 NAS의 IP, file은 공유 폴더 이름, /mnt/file는 마운트가 될 폴더, jb는 사용자 이름, 1234는 비밀번호입니다. 환경에 맞게 수정합니다. mount ...

Ubuntu 18.04 / 빠르게 다운로드하는 방법

우분투 다운로드 우분투 다운로드는 보통 우분투 홈페이지에서 합니다. 상단의 Downloads 메뉴를 클릭하고 안내를 따라가면 됩니다. 그런데, 우분투 홈페이지를 통해 다운로드를 받으면 전송 속도가 느릴 수 있습니다. 만약 너무 느리다면 가까운 미러 사이트에 직접 접속하여 다운로드해보세요. 빠르게 다운로드를 할 수 있습니다. 카카오 서버 한국이라면 카카오 서버가 빠릅니다. 우분투 페이지로 간 다음 원하는 버전을 선택합니다. 데스크톱 이미지와 ...

Rocky Linux 9 / hostname 변경하는 방법

Rocky Linux 9 / hostname 변경하는 방법

CLI 다음과 같이 명령하면 hostname을 출력한다. hostname 다음과 같이 명령하면 hostname을 rocky로 변경한다. hostnamectl set-hostname rocky GUI 의 Device Name에서 변경한다.

Ubuntu 16.04 Server / logrotate 설치하고 설정하기

우분투(Ubuntu)는 여러 작업의 내용을 로그(Log) 파일로 남깁니다. 예를 들어 웹서버 운영과 관련된 로그는 /var/log/apache2에 있습니다. 로그는 기본적으로 하나의 파일에 계속 추가하는 것이어서, 시간이 지날수록 파일의 크기가 커집니다. 로그 파일의 크기가 너무 커지면, 시스템이 느려지거나 다운되기도 합니다. 이러한 문제를 해결해주는 패키지가 logrotate입니다. 로그 파일이 일정 기준을 충족하면 기존 로그 파일을 다른 이름으로 변경하여 저장하고 ...

리눅스 / 명령어 / ls / 디렉토리와 파일 목록 출력하는 명령어

ls는 list의 약어로, 디렉토리와 파일 목록을 출력하는 명령어이다. ls 디렉토리명 디렉토리에 속한 디렉토리와 파일 목록을 출력한다. 숨김 파일은 나오지 않는다. 디렉토리명을 생략하면 현재 디렉토리에 속한 디렉토리와 파일 목록을 출력한다. 예를 들어 다음과 같이 명령하면 /var 디렉토리에 속한 디렉토리와 파일 목록을 출력한다. # ls /var ls -a, ls -l -a 옵션을 붙이면 숨김 파일도 출력한다. -l 옵션을 붙이면 소유자, 파일 ...

리눅스 / 하드디스크 파디션 만들기, 포맷하기, 마운트하기

리눅스에서 하드디스크 파티션 만들고, 포맷 하고, 마운트 하는 방법을 요약한다. 장착된 하드디스크 확인하기 ls 명령어로 컴퓨터에 장착된 하드디스크 정보를 출력할 수 있다. /dev/sda, /dev/sdb 등이 하드디스크, /dev/sda1 등이 파티션이다. # ls -l /dev/sd* brw-rw----. 1 root disk 8, 0 Oct 16 13:12 /dev/sda brw-rw----. 1 root disk 8, 1 Oct 16 13:12 /dev/sda1 brw-rw----. 1 ...

리눅스 / CD, ISO 마운트하는 방법

CD 마운트 마운트할 디렉토리 생셩 mkdir /aaa 마운트 # mount /dev/cdrom /aaa mount: /aaa: WARNING: source write-protected, mounted read-only. 마운트 해제 umount /aaa ISO 마운트 마운트할 디렉토리 생셩 mkdir /aaa 마운트 mount /root/Disc.iso /aaa -o loop mount: /aaa: WARNING: source write-protected, mounted read-only. 마운트 해제 umount /aaa

Ubuntu 18.04 / 메모

SSH 설정 설정 파일 /etc/ssh/sshd_config 포트 변경하기 다음 코드를 #Port 22 다음처럼 바꾼다. Port 1234 포트 번호는 자신이 원하는 것으로... root 계정 로그인 가능하게 만들기 다음 코드를 #PermitRootLogin prohibit-password 다음처럼 만든다. PermitRootLogin yes 설정 변경 적용하기 service ssh restart

Rocky Linux 8 / root 계정으로 ssh 접속 가능하게 설정하는 방법

Rocky Linux 8 / root 계정으로 ssh 접속 가능하게 설정하는 방법

Rocky Linux를 설치할 때 가능하게 설정하지 않았다면, root 계정으로 ssh 접속을 할 수 없다. 보안 상 권장되는 설정이나, 테스트나 공부 목적 등으로 root 계정으로 ssh 접속하는 게 더 좋은 상황이라면, 다음과 같이 하여 접속을 허용할 수 있다. vi나 nano 같은 텍스트 에디터로 /etc/ssh/sshd_config 파일을 연다. 제일 밑에 다음 코드를 추가하고, 저장한다. PermitRootLogin yes 다음과 같이 ...

Ubuntu 22.04 Server / 백신 프로그램 ClamAV 설치 및 사용법

ClamAV ClamAV는 리눅스에서 사용할 수 있는 백신 프로그램이다. 우분투 패키지에 포함되어 있으므로 apt 명령으로 쉽게 설치하고 사용할 수 있다. 설치 # apt install clamav 사용법 데이터베이스 업데이트 clamav-freshclam 서비스를 중지한다. # systemctl stop clamav-freshclam freshclam 명령으로 업데이트한다. # freshclam clamav-freshclam 서비스를 시작한다. # systemctl start clamav-freshclam 검사 home 디렉토리와 그 하위 디렉토리를 검사한다. # clamscan -r /home 검사 결과는 다음처럼 나온다. ----------- SCAN SUMMARY ----------- Known viruses: ...