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

 

같은 카테고리의 다른 글

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

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

리눅스 / 배포판 / 리눅스 민트(Linux Mint) - 역사, 특징, 장점

리눅스 민트의 역사 리눅스 민트(Linux Mint)는 2006년에 클레멘트 르페브르(Clement Lefebvre)가 시작한 리눅스 배포판입니다. 초기에는 우분투(Ubuntu) 기반으로 시작했으며, 이후 사용자가 쉽고 편리하게 사용할 수 있는 운영체제를 목표로 발전해왔습니다. 리눅스 민트는 특히 윈도우 사용자가 쉽게 전환할 수 있도록 직관적인 인터페이스와 다양한 멀티미디어 코덱을 기본으로 제공하는 것으로 유명합니다. 리눅스 민트의 특징 사용자 친화적 인터페이스 리눅스 민트는 특히 ...

리눅스 / IP 확인하는 방법

리눅스에서 IP 주소를 확인하는 방법은 여러 가지가 있으며, 이를 수행하는 데 사용되는 명령어와 도구는 다음과 같습니다. 이 명령어들은 모두 터미널에서 실행됩니다. ip addr 아래 명령어를 실행하면 모든 네트워크 인터페이스의 상세 정보가 표시됩니다. IP 주소는 inet 항목에서 확인할 수 있습니다. # ip addr 1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen ...

Ubuntu 24.04 / 언어 변경하는 방법

현재 언어 확인하기 locale 명령어로 현재 언어를 확인할 수 있다. # locale LANG=en_US.UTF-8 LANGUAGE= LC_CTYPE="en_US.UTF-8" LC_NUMERIC="en_US.UTF-8" LC_TIME="en_US.UTF-8" LC_COLLATE="en_US.UTF-8" LC_MONETARY="en_US.UTF-8" LC_MESSAGES="en_US.UTF-8" LC_PAPER="en_US.UTF-8" LC_NAME="en_US.UTF-8" LC_ADDRESS="en_US.UTF-8" LC_TELEPHONE="en_US.UTF-8" LC_MEASUREMENT="en_US.UTF-8" LC_IDENTIFICATION="en_US.UTF-8" LC_ALL= 언어 추가하기 사용 가능한 언어는 locale -a로 확인할 수 있다. # locale -a C C.utf8 en_US.utf8 POSIX 예를 들어 한국어를 추가하고 싶다면 아래와 같이 명령한다. # apt install language-pack-ko locale -a로 설치 확인을 한다. # locale -a C C.utf8 en_US.utf8 ko_KR.utf8 POSIX 언어 변경하기 다음과 같이 명령하면 사용하는 언어가 한국어로 바뀐다. update-locale LANG=ko_KR.utf8 로그아웃 후 다시 로그인하거나, 컴퓨터를 다시 시작하면 ...

리눅스 / 명령어 / cp - 복사하는 명령어, mv - 이동하는 명령어

cp는 copy의 약자로 복사하는 명령어, mv는 move의 약자로 이동하는 명령어이다. 복사하기 abc.txt 파일을 def.txt로 이름을 바꾸어 복사한다. cp abc.txt def.txt xyz라는 디렉토리가 없다면 abc.txt 파일을 xyz 파일로 복사한다. xyz라는 디렉토리가 있다면 xyz 디렉토리 안에 abc.txt 파일을 복사한다. cp abc.txt xyz abc.txt 파일을 xyz 디렉토리 안에 def.txt라는 이름으로 복사한다. cp abc.txt xyz/def.txt abc가 디렉토리이고 xyz라는 디렉토리가 없다면, abc 디렉토리를 xyz로 ...

리눅스 / 커널

리눅스 커널은 리눅스 운영체제의 핵심 구성 요소로, 시스템 하드웨어와 소프트웨어 간의 중재자 역할을 합니다. 커널은 시스템 자원을 관리하고, 프로세스 간의 통신을 지원하며, 기본적인 보안과 안정성을 제공합니다. 리눅스 커널은 자유 소프트웨어 및 오픈 소스 소프트웨어 개발 및 배포 모델에 따라 개발됩니다. 리눅스 커널의 주요 기능 프로세스 관리 프로세스 생성 및 종료 : 커널은 새로운 ...

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

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

Ubuntu 22.04 Server / 원격 데스크톱으로 연결하는 방법

Ubuntu 22.04 Server / 원격 데스크톱으로 연결하는 방법

GUI 설치 우분투에 GUI를 설치한다. # apt install ubuntu-desktop-minimal xrdp 설치 xrdp를 설치한다. # apt install xrdp 방화벽 설정 원격 데스크톱은 3389 포트를 사용하므로, 방화벽을 사용하고 있다면 포트를 열어 준다. ufw allow 3389/tcp 원격 데스크톱 연결 원격 데스크톱으로 접속한다. 아래와 같은 창이 뜨는데, 를 클릭한다. 계정 정보를 입력하고 를 클릭하면... 원격지에서 GUI로 우분투를 즐길 수 있다.

CentOS 7 / Samba / 설치하고 공유 폴더 만드는 방법

CentOS 7 / Samba / 설치하고 공유 폴더 만드는 방법

Samba 설치 Samba 패키지 이름은 samba입니다. yum install samba 방화벽 설정 Samba가 사용하는 포트를 열어줍니다. firewall-cmd --permanent --zone=public --add-service=samba 방화벽을 다시 로드합니다. firewall-cmd --reload 참고 : CentOS 7 / firewall-cmd 명령어로 방화벽 관리하기 SELinux SELinux를 적절히 설정하거나 끕니다. 참고 : CentOS 7 / SELinux 끄는 방법 Samba 사용자 추가 사용자가 Samba를 사용할 수 있도록 해줍니다. 만약 사용자계정이 user1이라면 다음과 같이 합니다. smbpasswd -a user1 Samba 설정 Samba 설정 ...

Ubuntu 16.04 / SASS 설치하는 방법

우분투 16.04에 SASS를 설치하는 방법은 두 가지가 있습니다. 방법 1 apt install ruby-sass 방법 2 apt install ruby gem install sass 설치되었는지 확인하는 방법 sass -v SASS 버전이 출력되면 제대로 설치된 것입니다. Sass 3.4.23 (Selective Steve) 참고 최신 버전의 SASS를 사용하고 싶다면 방법 2로 설치합니다.