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

 

같은 카테고리의 다른 글

리눅스 / 커널 / 버전 확인하는 방법

리눅스 커널 버전을 확인하는 방법은 여러 가지가 있습니다. 그 중 자주 사용하는 방법 두 가지를 소개합니다. uname uname 명령어는 시스템 정보를 출력하는 데 사용됩니다. -r 옵션을 사용하여 커널 버전을 확인할 수 있습니다. # uname -r 6.8.0-35-generic hostnamectl hostnamectl 명령어는 시스템의 호스트 이름과 관련된 정보를 관리하고 표시합니다. 여기에는 커널 버전 정보도 포함됩니다. # hostnamectl Static hostname: ubuntu-24-01 ...

리눅스 / RAID / Linear RAID, RAID0, RAID1, RAID5, RAID6

RAID 뜻과 종류 RAID Redundant Array of Inexpensive Disk or Redundant Array of Independent Disk 여러 개의 하드디스크를 하나처럼 사용하게 하는 기술. 예를 들어 1TB 하드디스크 두 개를 묶어서 2TB 하드디스크처럼 사용할 수 있다. 크게 하드웨어 RAID와 소프트웨어 RAID로 구분할 수 있다. 하드웨어 RAID는 성능이 좋으나 비싸다. 소프트웨어 RAID는 운영체제에서 지원하는 것으로 OS RAID라고도 한다. Linear RAID 두 ...

CentOS 7 / SSH / 포트 변경하는 방법

CentOS 7 / SSH / 포트 변경하는 방법

리눅스 서버에 SSH 접속을 하는 공격이 있습니다. SSH Brute Force라고 하는데, 여러 아이디와 비밀번호로 로그인을 시도하는 공격입니다. 이 공격을 방어하는 방법은 여러가지가 있습니다. root 계정으로 로그인 못하게 하기 암호를 복잡하게 만들기 접속 가능 IP를 정하기 SSH 포트 번호 바꾸기 이 중에서 SSH 포트 번호 바꾸는 방법을 정리해보겠습니다. CentOS 7 기준이며, 포트 번호를 1980으로 바꾼다고 가정하겠습니다. SSH 설정 파일 ...

Ubuntu / 설치 USB 만드는 방법

ODD가 없는 컴퓨터에 OS를 설치하는 방법은 두가지입니다. 첫번째는 휴대용 ODD를 이용하는 것이고, 두번째는 USB에 설치 파일을 넣어서 이용하는 것입니다. 두번째 방법이 간편하기는 하지만 설치용 USB를 만드는 게 좀 번거롭습니다. 하지만, 우분투(Ubuntu) 설치용 USB는 몇 번의 클릭으로 쉽게 만들 수 있습니다. 우분투 다운로드 원하는 우분투 버전을 다운로드 받습니다. Universal USB Installer 다운로드 다음의 링크에서 Universal USB Installer를 다운로드 ...

리눅스 / 게이트웨이(gateway) 확인하는 방법

리눅스에서 네트워크 정보는 주로 ifconfig, ip addr 명령어로 확인한다. 그런데, gateway 정보는 나오지 않는다. 만약 gateway 정보가 필요하다면 route 명령어를 사용한다. Ubuntu애서 명령어가 없다고 나오면 net-tools를 설치한다. apt install net-tools

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

Ubuntu 16.04 Server / PHP / 메모리 늘리는 방법

PHP 설정은 php.ini에서 한다. Ubuntu 16.04에서 php.ini의 위치는 /etc/php/7.0/apache2/php.ini 이다. PHP 버전에 따라 7.0은 다른 숫자일 수 있다. 메모리를 늘리기 위해 수정해야 할 것은 memory_limit이다. 기본값은 128M이다. 128을 적절히 변경한다. memory_limit = 128M 변경한 설정이 적용되도록 하려면 웹서버를 다시 시작하거나 다시 로드한다. Apache 웹서버라면 다음과 같이 명령하여 다시 시작할 수 있고, # service apache2 restart 다음과 같이 ...

리눅스 / 명령어 / mkdir / 디렉토리 만드는 명령어

mkdir은 make directory의 약자로, 디렉토리를 만드는 명령어이다. abc 디렉토리를 만든다. # mkdir abc abc 디렉토리 아래에 def 디렉토리를 만든다. 만약 abc 디렉토리가 없다면 def 디렉토리를 만들 수 없다는 메시지가 나온다. # mkdir abc/def p 옵션을 붙이면 abc 디렉토리가 없어도 abc 디렉토리를 만든 후에 def 디렉토리를 만든다. # mkdir -p abc/def 리눅스 / 명령어 / rm / 파일 ...

Ubuntu 20.04 Server / 설치하기

Ubuntu 20.04 Server / 설치하기

다운로드 Ubuntu Server 다운로드 페이지는 다음과 같다. https://ubuntu.com/download/server 최신 버전에 대한 안내가 주로 있으므로, 구버전을 다운로드하고 싶다면 아래 링크가 편하다. https://mirror.kakao.com/ubuntu-releases/ 가상 머신에 설치한다면 다운로드한 ISO 파일을 그대로 사용하면 되고, 물리 서버에 설치한다면 Rufus 같은 툴을 이용하여 부팅 USB를 만든다. 설치 설치 미디어로 부탕하고 잠시 기다리면 언어를 선택하는 화면이 나온다. 원하는 언어를 선택하고 엔터키를 누른다. 키보드 레이아웃을 선택한다. 네트워크 ...

Ubuntu Server / 메모

MariaDB / 포트 변경 MariaDB의 기본 접속 포트는 3306입니다. 이를 다른 포트로 변경하고 싶다면 /etc/mysql/mariadb.conf.d/50-server.cnf를 수정합니다. port = 3306 을 찾아서 원하는 포트로 변경한 후 저장합니다. 그리고 MariaDB를 재시작합니다. service mysql restart MariaDB / Can't connect to MySQL server on ... (10061) 다음과 같은 에러를 만났다면... Can't connect to MySQL server on ... (10061) /etc/mysql/mariadb.conf.d/50-server.cnf에 있는 bind-address = 127.0.0.1 를 ...