리눅스 / 명령어 / 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/>

 

같은 카테고리의 다른 글

Ubuntu 18.04 / 메모

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

리눅스 / chown, chmod / 파일 또는 디렉토리 소유자, 소유그룹, 권한 설정

chown과 chmod는 파일 및 디렉토리의 권한과 소유자를 관리하는 데 사용되는 Linux 명령어입니다. 정보 확인 ls 명령어에 -l 옵션을 붙여서 파일 또는 디렉토리의 권한과 소유자(그룹)을 확인할 수 있습니다. 제일 앞에 있는 문자는 디렉토리인지 파일인지는 나타냅니다. d는 디렉토리라는 뜻이고, -는 파일이라는 뜻입니다. 그 다음 3개의 문자열은 소유자의 권한을, 그 다음 3개의 문자열은 소유그룹의 권한을, 그 다음 ...

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 ...

리눅스 / 명령어 / history

리눅스를 쓰다 보면 자주 입력한 명령어를 다시 보고 싶거나, 실수로 종료한 터미널에서 이전 작업 기록이 필요할 때가 있죠. 이럴 때 유용하게 사용할 수 있는 명령어가 바로 history입니다.

CentOS 8 / Squid로 Proxy Server 만드는 방법

CentOS 8 / Squid로 Proxy Server 만드는 방법

리눅스로 프록시 서버(Proxy Server)를 만들 때 스퀴드(Squid)를 주로 사용합니다. 오픈 소스이고, 대부분의 리눅스 배포판에 패키지로 포함되어 있습니다. 스퀴드(squid)는 대중적인 오픈 소스(GPL)소프트웨어 프록시 서버이자 웹 캐시이다. 반복된 요청을 캐싱함으로 웹서버의 속도를 향상시키는 것부터, 네트워크 자원을 공유하려는 사람들에게 웹, DNS와 다른 네트워크 검색의 캐싱을 제공하고, 트래픽을 걸러줌으로써 안정성에 도움을 주는 등에 이르기까지 광범위 ...

Ubuntu 18.04 / 해상도 변경하는 방법

Ubuntu 18.04 / 해상도 변경하는 방법

Ubuntu 18.04 Desktop에서 해상도 변경하는 방법입니다. 바탕화면에서 마우스 우클릭을 합니다. 를 클릭합니다. 왼쪽 메뉴에서 를 클릭합니다. 왼쪽 메뉴에서 를 클릭하고, 오른쪽에서 해상도를 선택합니다. 오른쪽 위의 버튼을 클릭합니다. 를 클릭합니다.

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

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

Rocky Linux 9 / hostname 변경하는 방법

Rocky Linux 9 / hostname 변경하는 방법

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

리눅스 / 명령어

명령어 개요 adduser 사용자 추가하는 명령어. alias 명령어 별칭을 만든다. cal calendar. 달력을 출력하는 명령어. cat concatenate. 파일 내용 출력하는 명령어. cd change directory. 다른 디렉토리로 이동하는 명령어. chmod 파일 또는 디렉토리의 읽기, 쓰기, 실행 권한 설정하는 명령어 chown 파일 또는 디렉토리의 소유자(그룹) 설정하는 명령어 clear 터미널 화면의 내용을 다 지운다. cp copy. 파일 또는 디렉토리 복사. du disk usage. 디스크 사용량 출력. file 파일의 종류를 출력하는 명령어 find 파일 또는 디렉토리를 검색하는 명령어 free 메모리 사용량 ...

Ubuntu 22.04 Server / NGINX / 설치와 설정

Ubuntu 22.04 Server / NGINX / 설치와 설정

Nginx는 높은 성능과 안정성을 제공하는 웹 서버 소프트웨어로, 웹 서버 외에도 리버스 프록시, 로드 밸런서, 메일 프록시 등의 기능을 수행할 수 있다. Igor Sysoev가 2004년에 처음 개발했으며, 현재는 오픈 소스 소프트웨어로 널리 사용되고 있다. 가정 Ubuntu 22.04 Server의 IP는 192.168.3.242이고, 내 컴퓨터에서 IP로 접근 가능하다. 내 컴퓨터의 OS는 Windows이다. 설치 nginx 패키지 설치 다음과 같이 명령하여 ...