grep 명령어 (AIX 5.3·6.1)

핵심 정리

  • 파일이나 표준 입력에서 패턴과 일치하는 줄을 찾아 표준 출력에 씁니다.
  • 패턴은 기본이 기본 정규 표현식(BRE)입니다. -E는 확장 정규 표현식(ERE, egrep과 같음), -F는 고정 문자열(fgrep과 같음)입니다.
  • 자주 쓰는 플래그는 -i(대소문자 무시), -v(일치하지 않는 줄), -c(개수), -l(파일 이름만), -n(줄 번호), -w(단어), -x(줄 전체), -q(출력 없이 종료 상태만)입니다.
  • AIX에만 있는 것은 -p(일치한 줄이 든 문단 전체 출력)입니다. -H, -L, -b는 리눅스(GNU grep)와 뜻이 다릅니다.
  • 종료 상태는 0(찾음), 1(못 찾음), 1보다 큼(구문 오류나 파일 접근 실패)입니다.
  • AIX 5.3과 6.1 문서의 내용이 같습니다.
항목 내용
버전 AIX 5.3, AIX 6.1 (두 버전 내용 같음)
원문 IBM Commands Reference, Volume 2 — 5.3은 626쪽, 6.1은 685쪽
파일 /usr/bin/grep
관련 명령어 egrep, fgrep, ed, sed

목적

파일에서 패턴을 찾습니다.

영어 원문

Purpose

Searches for a pattern in a file.

구문

text
grep [ -E | -F ] [ -i ] [ -h ] [ -H ] [ -L ] [ -r | -R ] [ -s ] [ -u ] [ -v ] [ -w ] [ -x ] [ -y ]
     [ [ [ -b ] [ -n ] ] | [ -c | -l | -q ] ] [ -p [ Separator ] ]
     { [ -e PatternList ... ] [ -f PatternFile ... ] | PatternList ... } [ File ... ]

설명

grep 명령은 Pattern 매개변수로 지정한 패턴을 찾아, 일치하는 줄을 모두 표준 출력에 씁니다. 패턴은 ed나 egrep 명령 방식의 제한된 정규 표현식입니다. grep 명령은 간결한 비결정적(non-deterministic) 알고리즘을 씁니다.

File 매개변수에 파일 이름을 둘 이상 지정하면, 일치한 줄과 함께 그 줄이 든 파일의 이름을 표시합니다.

셸에서 특별한 뜻을 갖는 문자($, *, [, |, ^, (, ), \)를 Pattern 매개변수에 쓸 때는 따옴표로 감싸야 합니다. Pattern 매개변수가 단순한 문자열이 아니면 보통 패턴 전체를 작은따옴표로 감쌉니다.

[a-z] 같은 식에서 -(빼기 부호)는 현재 대조 순서(collating sequence)에 따른 범위를 뜻합니다. 대조 순서는 문자 범위에 쓸 동치 클래스(equivalence class)를 정의할 수 있습니다.

파일을 지정하지 않으면 grep은 표준 입력을 읽습니다.

참고

  1. 특수 파일(장치 파일)에는 grep 명령을 실행하지 마세요. 결과를 예측할 수 없습니다.
  2. 입력 줄에 NULL 문자가 들어 있으면 안 됩니다.
  3. 입력 파일은 줄바꿈 문자로 끝나야 합니다.
  4. 정규 표현식은 줄바꿈 문자와 일치하지 않습니다.
  5. 플래그 중 일부는 함께 쓸 수 있지만, 어떤 플래그는 다른 플래그보다 우선합니다. 예를 들어 -l 플래그는 다른 모든 플래그보다 우선합니다. -E와 -F를 함께 쓰면 마지막에 쓴 것이 적용됩니다.
영어 원문

Description

The grep command searches for the pattern specified by the Pattern parameter and writes each matching line to standard output. The patterns are limited regular expressions in the style of the ed or egrep command. The grep command uses a compact non-deterministic algorithm.

The grep command displays the name of the file containing the matched line if you specify more than one name in the File parameter. Characters with special meaning to the shell ($, *, [, |, ^, (, ), \) must be in quotation marks when they appear in the Pattern parameter. When the Pattern parameter is not a simple string, you usually must enclose the entire pattern in single quotation marks. In an expression such as [a-z], the - (minus sign) cml specifies a range, according to the current collating sequence. A collating sequence may define equivalence classes for use in character ranges. If no files are specified, grep assumes standard input.

Notes:

  1. Do not run the grep command on a special file because it produces unpredictable results.
  2. Input lines should not contain the NULL character.
  3. Input files should end with the newline character.
  4. The newline character will not be matched by the regular expressions.
  5. Although some flags can be specified simultaneously, some flags override others. For example, the -l option takes precedence over all other flags. And if you specify both the -E and -F flags, the last one specified takes priority.

플래그

플래그 설명
-b 찾은 줄 앞에 그 줄이 있던 블록 번호를 붙입니다. 문맥으로 디스크 블록 번호를 찾을 때 씁니다. 표준 입력이나 파이프로 받은 입력에는 쓸 수 없습니다.
-c 일치한 줄의 개수만 표시합니다.
-E 각 패턴을 확장 정규 표현식(ERE)으로 다룹니다. 빈(NULL) ERE는 모든 줄과 일치합니다. grep -E는 egrep 명령과 같지만, 오류·사용법 메시지가 다르고 -s 플래그의 동작이 다릅니다.
-e PatternList 검색 패턴을 하나 이상 지정합니다. 단순 패턴과 같지만 패턴이 -(빼기)로 시작할 때 유용합니다. 패턴끼리는 줄바꿈 문자로 나눕니다. 빈 패턴은 줄바꿈 문자 두 개를 잇달아 쓰거나, 따옴표 뒤에 줄바꿈 문자를 써서("\n) 지정합니다. -E나 -F를 함께 쓰지 않으면 각 패턴을 기본 정규 표현식(BRE)으로 다룹니다. -e와 -f는 여러 번 쓸 수 있습니다. 지정한 패턴을 모두 써서 줄을 비교하지만, 평가 순서는 정해져 있지 않습니다.
-F 각 패턴을 정규 표현식이 아닌 문자열로 다룹니다. 빈 문자열은 모든 줄과 일치합니다. grep -F는 fgrep 명령과 같지만, 오류·사용법 메시지가 다르고 -s 플래그의 동작이 다릅니다.
-f PatternFile 검색 패턴이 든 파일을 지정합니다. 패턴은 줄바꿈 문자로 나누며, 빈 줄은 빈 패턴으로 봅니다. -E나 -F를 함께 쓰지 않으면 각 패턴을 기본 정규 표현식(BRE)으로 다룹니다.
-h 일치한 줄 앞에 그 줄이 든 파일의 이름을 붙이지 않습니다. 파일을 여러 개 지정했을 때 파일 이름을 숨깁니다.
-H -r이나 -R을 쓸 때, 명령줄에 지정한 심볼릭 링크가 디렉터리를 가리키면 그 디렉터리와 그 아래 모든 파일을 검색합니다.
-i 비교할 때 대소문자를 무시합니다.
-l 일치한 줄이 있는 파일의 이름만 (한 번씩) 나열합니다. 파일 이름은 줄바꿈 문자로 나뉩니다. 표준 입력을 검색했다면 (StandardInput)이라는 경로 이름을 돌려줍니다. -l을 -c, -n과 어떻게 함께 써도 -l만 쓴 것처럼 동작합니다.
-L -r이나 -R을 쓸 때, 명령줄에 지정했거나 탐색 중에 만난 심볼릭 링크가 디렉터리를 가리키면 그 디렉터리와 그 아래 모든 파일을 검색합니다. -H와 -L을 함께 쓰면 명령줄에서 마지막에 쓴 것이 적용됩니다.
-n 각 줄 앞에 파일 안에서의 줄 번호를 붙입니다. 파일마다 1부터 다시 셉니다.
-p[Separator] 일치한 줄이 든 문단 전체를 표시합니다. 문단은 Separator 매개변수로 지정한 문단 구분자로 나뉘며, 구분자는 검색 패턴과 같은 형식의 패턴입니다. 구분자가 든 줄은 구분에만 쓰이고 출력에는 들어가지 않습니다. 기본 구분자는 빈 줄입니다.
-q 일치하는 줄이 있든 없든 표준 출력에 아무것도 쓰지 않습니다. 선택된 줄이 있으면 종료 상태 0으로 끝납니다. -q를 -c, -l, -n과 어떻게 함께 써도 -q만 쓴 것처럼 동작합니다.
-r 디렉터리를 재귀적으로 검색합니다. 기본적으로 디렉터리를 가리키는 링크를 따라갑니다.
-R 디렉터리를 재귀적으로 검색합니다. 기본적으로 디렉터리를 가리키는 링크를 따라가지 않습니다.
-s 없거나 읽을 수 없는 파일 때문에 나오는 오류 메시지를 숨깁니다. 다른 오류 메시지는 숨기지 않습니다.
-u 출력을 버퍼에 모으지 않고 바로 씁니다.
-v 패턴과 일치하지 않는 줄을 모두 표시합니다.
-w 단어 단위로 찾습니다.
-x 패턴과 정확히, 다른 문자 없이 일치하는 줄만 표시합니다.
-y 비교할 때 대소문자를 무시합니다.

매개변수

매개변수 설명
PatternList 검색에 쓸 패턴을 하나 이상 지정합니다. -e 플래그로 지정한 것처럼 다룹니다.
File 패턴을 찾을 파일의 이름입니다. 지정하지 않으면 표준 입력을 씁니다.
영어 원문

Flags

Item Description
-b Precedes each line by the block number on which it was found. Use this flag to help find disk block numbers by context. The -b flag cannot be used with input from stdin or pipes.
-c Displays only a count of matching lines.
-E Treats each pattern specified as an extended regular expression (ERE). A NULL value for the ERE matches every line. Note: The grep command with the -E flag is the same as the egrep command, except that error and usage messages are different and the -s flag functions differently.
-e PatternList Specifies one or more search patterns. This works like a simple pattern but is useful when the pattern begins with a - (minus). Patterns should be separated by a new-line character. A NULL pattern can be specified by two adjacent new-line characters or a quotation mark followed by a new-line character ("\n). Each pattern is treated like a basic regular expression (BRE) unless the -E or -F flag is also specified. Multiple -e and -f flags are accepted by grep. All of the specified patterns are used when matching lines, but the order of evaluation is unspecified.
-F Treats each specified pattern as a string instead of a regular expression. A NULL string matches every line. Note: The grep command with the -F flag is the same as the fgrep command, except that error and usage messages are different and the -s flag functions differently.
-f PatternFile Specifies a file containing search patterns. Each pattern should be separated by a new-line character, and an empty line is considered a NULL pattern. Each pattern is treated like a basic regular expression (BRE), unless the -E or -F flag is also specified.
-h Prevents the name of the file containing the matching line from being appended to that line. Suppresses file names when multiple files are specified.
-H If the -r or -R option is specified and a symbolic link referencing a file of type directory is specified on the command line, grep will search the files of the directory referenced by the symbolic link and all the files in the file hierarchy below it.
-i Ignores the case (uppercase or lowercase) of letters when making comparisons.
-l Lists just the names of files (once) which contain matching lines. Each file name is separated by a new-line character. If standard input is searched, a path name of (StandardInput) is returned. The -l flag with any combination of the -c and -n flags behaves like the -l flag only.
-L If the -r or -R option is specified and a symbolic link referencing a file of type directory is specified on the command line or encountered during the traversal of a file hierarchy, grep shall search the files of the directory referenced by the symbolic link and all the files in the file hierarchy below it. If both -H and -L are specified, the last option specified on the command line takes effect.
-n Precedes each line with the relative line number in the file. Each file starts at line 1, and the line counter is reset for each file processed.
-p[Separator] Displays the entire paragraph containing matched lines. Paragraphs are delimited by paragraph separators, as specified by the Separator parameter, which are patterns in the same form as the search pattern. Lines containing the paragraph separators are used only as separators; they are never included in the output. The default paragraph separator is a blank line.
-q Suppresses all writing to standard output, regardless of matching lines. Exits with a zero status if an input line is selected. The -q flag with any combination of the -c, -l and -n flags behaves like the -q flag only.
-r Searches directories recursively. By default, links to directories are followed.
-R Searches directories recursively. By default, links to directories are not followed.
-s Suppresses error messages ordinarily written for nonexistent or unreadable files. Other error messages are not suppressed.
-u Causes output to be unbuffered.
-v Displays all lines not matching the specified pattern.
-w Does a word search.
-x Displays lines that match the specified pattern exactly with no additional characters.
-y Ignores the case of letters when making comparisons.
PatternList Specifies one or more patterns to be used during the search. The patterns are treated as if they were specified using the -e flag.
File Specifies a name of a file to be searched for patterns. If no File variable is given, the standard input is used.

종료 상태

값 뜻
0 일치하는 줄을 찾았습니다.
1 일치하는 줄이 없습니다.
1보다 큼 구문 오류가 있거나 파일에 접근할 수 없었습니다(일치한 줄이 있었더라도).
영어 원문

Exit Status

This command returns the following exit values:

Item Description
0 A match was found.
1 No match was found.
>1 A syntax error was found or a file was inaccessible (even if matches were found).

예제

  1. 패턴 일치 문자(*, ^, ?, [, ], \(, \), \{, \})가 든 패턴을 쓰려면 다음과 같이 입력합니다.
bash
grep "^[a-zA-Z]" pgm.s

pgm.s에서 첫 글자가 영문자인 줄을 모두 표시합니다.

  1. 패턴과 일치하지 않는 줄을 모두 표시하려면 다음과 같이 입력합니다.
bash
grep -v "^#" pgm.s

pgm.s에서 첫 글자가 #(샵)이 아닌 줄을 모두 표시합니다.

  1. file1 파일에서 abc나 xyz 문자열이 든 줄을 모두 표시하려면 다음과 같이 입력합니다.
bash
grep -E "abc|xyz" file1
  1. test2 파일에서 $(달러 기호)를 찾으려면 다음과 같이 입력합니다.
bash
grep \\$ test2

셸이 grep 명령에 \$(백슬래시 하나와 달러 기호)를 넘기게 하려면 \\(백슬래시 두 개)가 필요합니다. 백슬래시 하나는 grep 명령에게 다음 문자(이 예에서는 $)를 정규 표현식 문자가 아닌 글자 그대로 다루라고 알립니다. 백슬래시 같은 이스케이프 문자를 쓰지 않으려면 fgrep 명령을 씁니다.

  1. /tmp를 재귀적으로 검색하되 디렉터리를 가리키는 링크는 따라가지 않고, IBM이라는 단어가 든 파일을 찾으려면 다음 둘 중 하나를 입력합니다.
bash
grep -R IBM /tmp
grep -r -H IBM /tmp
  1. /tmp를 재귀적으로 검색하면서 링크도 따라가 IBM이라는 단어가 든 파일을 찾으려면 다음 둘 중 하나를 입력합니다.
bash
grep -r IBM /tmp
grep -R -L IBM /tmp
영어 원문

Examples

  1. To use a pattern that contains some of the pattern-matching characters *, ^, ?, [, ], \(, \), \{, and \}, enter: grep "^[a-zA-Z]" pgm.s. This displays every line in pgm.s whose first character is a letter.
  2. To display all lines that do not match a pattern, enter: grep -v "^#" pgm.s. This displays every line in pgm.s whose first character is not a # (pound sign).
  3. To display all lines in the file1 file that match either the abc or xyz string, enter: grep -E "abc|xyz" file1
  4. To search for a $ (dollar sign) in the file named test2, enter: grep \\$ test2. The \\ (double backslash) characters are necessary in order to force the shell to pass a \$ (single backslash, dollar sign) to the grep command. The \ (single backslash) character tells the grep command to treat the following character (in this example the $) as a literal character rather than an expression character. Use the fgrep command to avoid the necessity of using escape characters such as the backslash.
  5. To search recursively through /tmp to find files which have the word IBM without recursing through links pointing to directories, type: grep –R IBM /tmp OR grep –r -H IBM /tmp
  6. To search recursively through /tmp to find files which have the word IBM and recurse through links as well, type: grep –r IBM /tmp OR grep -R -L IBM /tmp

파일

파일 설명
/usr/bin/grep grep 명령이 들어 있습니다.

관련 정보

  • 명령어: egrep, fgrep, ed, sed
  • 입력과 출력 재지정(Input and output redirection)
영어 원문

Files

Item Description
/usr/bin/grep Contains the grep command.

Related reference: egrep Command, fgrep Command. Related information: ed command, sed command, Input and output redirection.

리눅스(GNU grep)와 다른 점

AIX 문서의 플래그 목록을 리눅스에서 흔히 쓰는 GNU grep과 견주면 같은 글자인데 뜻이 다른 것이 있습니다.

플래그 AIX 5.3·6.1 GNU grep
-H -r·-R과 함께, 명령줄에 쓴 디렉터리 링크를 따라감 줄 앞에 파일 이름을 붙임
-L -r·-R과 함께, 만나는 디렉터리 링크를 모두 따라감 일치하는 줄이 없는 파일의 이름만 표시
-b 디스크 블록 번호를 붙임 바이트 오프셋을 붙임
-r·-R -r은 디렉터리 링크를 따라가고 -R은 따라가지 않음 -R은 모든 링크를 따라가고 -r은 명령줄에 쓴 링크만 따라감
-p 일치한 줄이 든 문단 전체를 표시 없음

AIX 5.3·6.1 문서에는 -o(일치한 부분만), -A·-B·-C(앞뒤 줄), --color 같은 GNU 플래그가 없습니다.