grep 명령어 (Command) – AIX 6.1

grep 명령어 (Command)

목적 (Purpose)

파일에서 패턴을 검색합니다.

구문 (Syntaax)

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

구문 (Syntaax)

파일에서 패턴을 검색합니다.

grep 명령어는 Pattern 매개변수로 지정된 패턴을 검색하고, 일치하는 가 줄을 표준 출력(Standard output)으로 기록합니다.

이 패턴들을 ed 또는 egrep 명령어 스타일의 제한된 정규(regular expressions)입니다.

grep 명령어는 컴팩트한 비결정적(non-deterministic) 알고리즘을 사용합니다.
grep은 메모리를 적게 쓰면서도(Compact), 모든 가능성을 유연하게 탐색하는(Non-deterministic) 수학적 모델을 사용하여 줄 단위로 검색 결과를 뽑아낸다는 뜻

File 매개변수에 둘 이상의 이름을 지정하면 grep 명령어는 일치하는 줄이 포함된 파일의 이름을 표시합니다.

쉘(shell)에 특별한 의미가 있는 문자($, *, [, |, ^, (, ), \ )가 Pattern 매개변수에 포함될 경우 반드시 따옴표로 묶어야 합니다.

Pattern 매개변수가 단순한 문자열이 아닌 경우, 일반적으로 전체 패턴을 작은따옴표(‘ ‘)로 묶어야 합니다.

[a-z]와 같은 표현식에서 - (빼기 기호)는 현재 데이터 정렬 순서(collating sequence)에 따라 범위를 지정합니다.

데이터 정렬 순서는 문자 범위에 사용할 동치 클래스(equivalence classes)를 정의할 수 있습니다.

지정된 파일이 없는 경우, grep은 표준 입력(standard input)을 가정합니다.

# [a-z]와 데이터 정렬 순서
시스템의 설정에 따라서 아래와 같은 순서 가능하다.
a, A, b, B, c, C...
a, b, c... A, B, C...

# 동치 클래스 (Equivalence Classes)
프랑스어의 é, è, ê 같은 글자들은 다 'e' 계열
[[=e=]]라고 쓰면 e와 비슷하게 생긴 모든 글자를 한꺼번에 찾아주겠다는 기능

# 지정된 파일이 없으면 표준 입력(Standard Input)
보통 쓸 때: grep "error" log.txt (파일에서 찾음)
파일 안 쓸 때: cat log.txt | grep "error" (앞의 cat이 넘겨준 표준 입력에서 찾음)

참고 (Notes)

  • 예측할 수 없는 결과를 초래할 수 있으므로 특수 파일(special file)에서 grep 명령어를 실행하지 마십시오.
    입력 줄에는 NULL 문자가 포함되어서는 안 됩니다.
  • 입력 파일은 줄 바꿈(newline) 문자로 끝나야 합니다.
  • 줄 바꿈 문자는 정규식과 일치하지 않습니다.
  • 일부 플래그는 동시에 지정할 수 있지만, 특정 플래그는 다른 플래그를 무시(override)합니다.
    예를 들어, -l 옵션은 다른 모든 플래그보다 우선합니다. 또한 -E-F 플래그를 모두 지정하는 경우 마지막에 지정된 것이 우선순위를 갖습니다.

플래그 (Flags)

-b: 각 줄 앞에 해당 줄이 발견된 블록 번호를 표시합니다.
이 플래그를 사용하면 문맥별로 디스크 블록 번호를 찾는 데 도움이 됩니다.
-b 플래그는 표준 입력(stdin)이나 파이프(pipes)의 입력과 함께 사용할 수 없습니다.

-c: 일치하는 줄의 개수(count)만 표시합니다.

-E: 지정된 각 패턴을 확장 정규식(ERE)으로 취급합니다. NULL 값의 ERE는 모든 줄과 일치합니다.

  • 참고: -E 플래그를 사용한 grep 명령어는 오류 및 사용법 메시지가 다르고 -s 플래그의 기능이 다르다는 점을 제외하면 egrep 명령어와 동일합니다.

-e PatternList: 하나 이상의 검색 패턴을 지정합니다. 이는 단순 패턴처럼 작동하지만 패턴이 - (빼기 기호)로 시작할 때 유용합니다. 패턴은 줄 바꿈 문자로 구분해야 합니다. 두 개의 인접한 줄 바꿈 문자나 줄 바꿈 문자가 뒤따르는 따옴표("\n)로 NULL 패턴을 지정할 수 있습니다. -E 또는 -F 플래그가 함께 지정되지 않는 한, 각 패턴은 기본 정규식(BRE)으로 취급됩니다. 여러 개의 -e-f 플래그가 grep에서 허용됩니다. 지정된 모든 패턴은 줄을 일치시킬 때 사용되지만, 평가 순서는 지정되지 않습니다.

-F: 지정된 각 패턴을 정규식이 아닌 문자열(string)로 취급합니다. NULL 문자열은 모든 줄과 일치합니다.

  • 참고: -F 플래그를 사용한 grep 명령어는 오류 및 사용법 메시지가 다르고 -s 플래그의 기능이 다르다는 점을 제외하면 fgrep 명령어와 동일합니다.

-f PatternFile:
검색 패턴이 포함된 파일을 지정합니다.
각 패턴은 줄 바꿈 문자로 구분되어야 하며, 빈 줄은 NULL 패턴으로 간주됩니다.
-E 또는 -F 플래그가 함께 지정되지 않는 한, 각 패턴은 기본 정규식(BRE)으로 취급됩니다.

-h:
일치하는 줄에 해당 파일의 이름이 덧붙여 표시되는 것을 방지합니다.
여러 파일이 지정된 경우 파일 이름 표시를 억제합니다.

-H:
-r 또는 -R 옵션이 지정되고 디렉토리 유형의 파일을 참조하는 심볼릭 링크가 명령줄에 지정된 경우,
grep은 심볼릭 링크가 참조하는 디렉토리의 파일과 그 아래의 파일 계층 구조에 있는 모든 파일을 검색합니다.

-i:
비교를 수행할 때 문자의 대소문자(대문자 또는 소문자)를 무시합니다.

-l:
일치하는 줄이 포함된 파일의 이름만 (한 번) 나열합니다.
각 파일 이름은 줄 바꿈 문자로 구분됩니다.
표준 입력을 검색한 경우 (StandardInput)이라는 경로 이름이 반환됩니다.
-c-n 플래그의 조합과 함께 사용된 -l 플래그는 -l 플래그만 사용한 것과 같이 동작합니다.

-L:
-r 또는 -R 옵션이 지정되고 디렉토리 유형의 파일을 참조하는 심볼릭 링크가 명령줄에 지정되거나 파일 계층 구조 탐색 중 발견된 경우,
grep은 심볼릭 링크가 참조하는 디렉토리의 파일과 그 아래의 파일 계층 구조에 있는 모든 파일을 검색합니다.
-H-L이 모두 지정된 경우 명령줄에 마지막으로 지정된 옵션이 적용됩니다.

-n:
각 줄 앞에 파일 내의 상대적인 줄 번호를 표시합니다.
각 파일은 1번 줄부터 시작하며, 처리되는 각 파일마다 줄 카운터가 재설정됩니다.

-p [Separator]:
일치하는 줄이 포함된 전체 단락(paragraph)을 표시합니다.
단락은 Separator 매개변수로 지정된 단락 구분 기호로 구분되며, 이는 검색 패턴과 동일한 형식의 패턴입니다.
단락 구분 기호가 포함된 줄은 구분 기호로만 사용되며 출력에는 절대 포함되지 않습니다.
기본 단락 구분 기호는 빈 줄입니다.

-q:
일치하는 줄이 있는지 여부에 관계없이 표준 출력으로의 모든 쓰기를 억제합니다.
입력 줄이 선택되면 상태 값 0으로 종료됩니다.
-c, -l-n 플래그의 조합과 함께 사용된 -q 플래그는 -q 플래그만 사용한 것과 같이 동작합니다.

-r:
디렉토리를 재귀적으로 검색합니다.
기본적으로 디렉토리에 대한 링크는 따라갑니다(Recursive – Link Follow).

-R:
디렉토리를 재귀적으로 검색합니다.
기본적으로 디렉토리에 대한 링크는 따라가지 않습니다(Recursive – No Link Follow).

-s:
존재하지 않거나 읽을 수 없는 파일에 대해 일반적으로 표시되는 오류 메시지를 억제합니다.
다른 오류 메시지는 억제되지 않습니다.

-u:
출력을 버퍼링하지 않도록(unbuffered) 합니다.

-v:
지정된 패턴과 일치하지 않는 모든 줄을 표시합니다.

-w:
단어 검색을 수행합니다.

-x:
추가 문자 없이 지정된 패턴과 정확히 일치하는 줄을 표시합니다.

-y:
비교를 수행할 때 문자의 대소문자를 무시합니다.

PatternList:
검색 중에 사용할 하나 이상의 패턴을 지정합니다.
패턴은 -e 플래그를 사용하여 지정된 것처럼 취급됩니다.

File:
패턴을 검색할 파일의 이름을 지정합니다.
File 변수가 주어지지 않으면 표준 입력(standard input)이 사용됩니다.

종료 상태 (Exit Status)

이 명령어는 다음 종료 값을 반환합니다:

  • 0: 일치하는 항목을 찾았습니다.
  • 1: 일치하는 항목을 찾지 못했습니다.
  • >1: 구문 오류(syntax error)가 발견되었거나 파일에 액세스할 수 없습니다(일치하는 항목이 발견되었더라도).

예제 (Examples)

# 예제 1
*, ^, ?, [, ], \(, \), \{, \} 등의 일부 패턴 일치 문자가 포함된 패턴을 사용하려면 다음을 입력하십시오: 
grep "^[a-zA-Z]" pgm.s 
이 명령어는 첫 번째 문자가 영문자인 pgm.s 파일의 모든 줄을 표시합니다.

# 예제 2
패턴과 일치하지 않는 모든 줄을 표시하려면 다음을 입력하십시오: 
grep -v "^#" pgm.s 
이 명령어는 첫 번째 문자가 # (파운드 기호)가 아닌 pgm.s 파일의 모든 줄을 표시합니다.

# 예제 3
abc 또는 xyz 문자열과 일치하는 file1 파일의 모든 줄을 표시하려면 다음을 입력하십시오: 
grep -E "abc|xyz" file1

# 예제 4
test2라는 파일에서 $ (달러 기호)를 검색하려면 다음을 입력하십시오: 
grep \\$ test2 
쉘이 grep 명령어에 \$ (단일 백슬래시, 달러 기호)를 전달하도록 강제하려면 \\ (이중 백슬래시) 문자가 필요합니다. 
\ (단일 백슬래시) 문자는 grep 명령어에 다음 문자를 표현식 문자가 아닌 리터럴(literal) 문자로 취급하도록 지시합니다. 
(이 예시에서는 $)
백슬래시와 같은 이스케이프 문자를 사용하는 번거로움을 피하려면 fgrep 명령어를 사용하십시오.

# 예제 5
디렉토리를 가리키는 링크를 통해 재귀적으로 탐색하지 않고, 
IBM이라는 단어가 포함된 파일을 찾기 위해 /tmp 디렉토리를 재귀적으로 검색하려면 다음을 입력하십시오: 
grep -R IBM /tmp 또는 (OR) grep -r -H IBM /tmp

# 예제 6
링크를 포함하여 IBM이라는 단어가 포함된 파일을 찾기 위해 /tmp 디렉토리를 재귀적으로 검색하려면 다음을 입력하십시오: 
grep -r IBM /tmp 
또는 (OR) 
grep -R -L IBM /tmp

파일 (Files)

  • /usr/bin/grep: grep 명령어를 포함합니다.

관련 참조 (Related reference):

  • egrep Command” on page 347
  • fgrep Command” on page 514

관련 정보 (Related information):

  • sed command
  • Input and output redirection

원문

Commands Reference, Volume 2, d – h.PDF 685p

grep Command
Purpose
Searches for a pattern in a file.
Syntax
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 ... ]
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. Input lines
should not contain the NULL character.
2. Input files should end with the newline character.
3. The newline character will not be matched by the regular expressions.
4. 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.
g 685
Flags
Item-b-c-E-e PatternList-F-f PatternFile-h-H-i
Item-l-L-n-p[Separator]-q-r-R-s-u-v-w-x-y
PatternList
File
Description
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.
Displays only a count of matching lines.
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.
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.
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.
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.
Prevents the name of the file containing the matching line from being appended to that line.
Suppresses file names when multiple files are specified.
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.
Ignores the case (uppercase or lowercase) of letters when making comparisons.
Description
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.
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.
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.
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.
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.
Searches directories recursively. By default, links to directories are followed.
Searches directories recursively. By default, links to directories are not followed.
Suppresses error messages ordinarily written for nonexistent or unreadable files. Other error
messages are not suppressed.
Causes output to be unbuffered.
Displays all lines not matching the specified pattern.
Does a word search.
Displays lines that match the specified pattern exactly with no additional characters.
Ignores the case of letters when making comparisons.
Specifies one or more patterns to be used during the search. The patterns are treated as if they
were specified using the -e flag.
Specifies a name of a file to be searched for patterns. If no File variable is given, the standard
input is used.
686 AIX Version 6.1: Commands Reference, Volume 2, d - h
Exit Status
This command returns the following exit values:
Item
0
1
>1
Description
A match was found.
No match was found.
A syntax error was found or a file was inaccessible (even if matches were found).
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
Files
g 687
Item
/usr/bin/grep
Description
Contains the grep command.
Related reference:
“egrep Command” on page 347
“fgrep Command” on page 514
Related information:
sed command
Input and output redirection

댓글 달기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다

위로 스크롤