본문 바로가기

Study/Linux

linux grep

출처 : http://innu.pe.kr/tt/43


GREP

Section: User Commands (1)
Updated: 2000/02/26
Index
Return to Main Contents

NAME

grep, egrep, fgrep - print lines matching a pattern

패턴과 일치하는 라인을 출력한다.


SYNOPSIS

grep [options] PATTERN [FILE...]
grep [options] [-e PATTERN | -f FILE] [FILE...]

DESCRIPTION

Grep searches the named input FILEs (or standard input if no files are named, or the file name - is given) for lines containing a match to the given PATTERN. By default, grep prints the matching lines.

In addition, two variant programs egrep and fgrep are available. Egrep is the same as grep -E. Fgrep is the same as grep -F.

grep는 입력파일(파일이 없거나 - 이면 표준입력)로부터 주어진 패턴과 매치되는 라인을 찾는다.

기본적으로 grep는 매칭되는 라인을 출력한다.

확장된 egrep와 fgrep역시 유용하다.

egrep는 grep -E 와 같고 fgrep는 grep -F와 같다.

OPTIONS

-A NUM, --after-context=NUM
Print NUM lines of trailing context after matching lines.
패턴매칭라인 이후의 라인을 NUM수만큼 출력한다

-a, --text
Process a binary file as if it were text; this is equivalent to the --binary-files=text option.
기본적으로 grep는 바이너리 파일을 처리할 수없다.
그런데 바이너리파일을 텍스트파일처럼 처리할 수있는 옵션이 -a 옵션이다.
--binary-files=text 와 동등하다.

-B NUM, --before-context=NUM
Print NUM lines of leading context before matching lines.
패턴매칭라인 이전의 내용을 NUM수만큼 출력한다.
-A와는 반대되는 옵션이라고 생각하면 된다.

-C [NUM], -NUM, --context[=NUM]
Print NUM lines (default 2) of output context.
출력물 앞뒤 전후의 주어진 라인만큼 출력한다(패턴매칭 라인은 포함하지 않고 기본 2라인)

-b, --byte-offset
Print the byte offset within the input file before each line of output.
패턴매칭되기전 라인의 바이트수를 출력한다.

--binary-files=TYPE
If the first few bytes of a file indicate that the file contains binary data, assume that the file is of type TYPE. By default, TYPE is binary, and grep normally outputs either a one-line message saying that a binary file matches, or no message if there is no match. If TYPE is without-match, grep assumes that a binary file does not match; this is equivalent to the -I option. If TYPE is text, grep processes a binary file as if it were text; this is equivalent to the -a option. Warning: grep --binary-files=text might output binary garbage, which can have nasty side effects if the output is a terminal and if the terminal driver interprets some of it as commands.
파일 헤더가 바이너리를 포함한 파일을 가리키면 TYPE형 파일이라고 인식한다.
기본은 binary이다.
grep는 일반적으로 바이너리 파일을 알 수있는 하나의 메시지를 출력하거나 매치되지 않으면 메세지를 출력하지 않는다.
TYPE이 without-match 이면 grep는 바이너리파일이 매치되지 않는걸로 생각한다.
이는 -I(대문자 I) 옵션과 동등하다.
만약 TYPE이 text이면 grep은 텍스트파일로써 바이너리를 처리한다.
이는 -a 옵션과 동등하다.

주의: grep --binary-files=text 는 binary garbage를 출력할 수도 있다.
출력이 터미널이거나 터미널이 특정한 command로써 해석을 한다면 그의 부작용으로 출력이 지저분해지기도 한다.

-c, --count
Suppress normal output; instead print a count of matching lines for each input file. With the -v, --invert-match option (see below), count non-matching lines.
출력을 억제한다. 대신 각 입력파일과 매치되는 라인의 수를 출력한다.
-v, --invert-match 옵션과 함께 쓰이면 매치되지 않는 라인의 수를 출력한다.

-d ACTION, --directories=ACTION
If an input file is a directory, use ACTION to process it. By default, ACTION is read, which means that directories are read just as if they were ordinary files. If ACTION is skip, directories are silently skipped. If ACTION is recurse, grep reads all files under each directory, recursively; this is equivalent to the -r option.
입력파일이 디렉토리이면 ACTION 처리한다.
기본적으로 ACTION은 read이고, 이는 원본파일인것처럼 디렉토리가 읽는다는것을 의미한다. ACTION이 skip이면 skip된다. ACTION이 recurse이면 grep은 각각의 디렉토리이하를 순환적으로 읽어들인다. 이는 -r 옵션과 동등하다.
 
-E, --extended-regexp
Interpret PATTERN as an extended regular expression (see below).
확장 정규표현식으로 패턴을 해석한다.

-e PATTERN, --regexp=PATTERN
Use PATTERN as the pattern; useful to protect patterns beginning with -.
패턴으로 PATTERN을 사용한다. - 으로 시작하는 패턴을 보호하는데 유용하다.

-F, --fixed-strings
Interpret PATTERN as a list of fixed strings, separated by newlines, any of which is to be matched.
newline으로 분리된 고정된 문자열의 리스트로써 패턴을 해석한다.

-f FILE, --file=FILE
Obtain patterns from FILE, one per line. The empty file contains zero patterns, and therefore matches nothing.
파일로부터 패턴을 얻는다(파일의 라인마다)
공백파일은 zero 패턴을 포함한다. 그러므로 매치되는것이 없다.

-G, --basic-regexp
Interpret PATTERN as a basic regular expression (see below). This is the default.
정규표현식으로써 PATTERN을 해석하고 이것이 기본이다.

-H, --with-filename
Print the filename for each match.
매칭되는 파일명을 출력한다.

-h, --no-filename
Suppress the prefixing of filenames on output when multiple files are searched.
여러개의 파일이 검색되었을때 -H 옵션처럼 앞에 파일명을 출력하지 않는다.

--help
Output a brief help message.
help 메세지를 출력한다.

-I
Process a binary file as if it did not contain matching data; this is equivalent to the --binary-files=without-match option.
매칭된 데이터를 포함하지 않는것처럼 바이너리 파일을 처리한다.
binary-files=without-match 옵션과 동등하다.

-i, --ignore-case
Ignore case distinctions in both the PATTERN and the input files.
주어진 패턴이나 입력파일에서 대소문자를 무시한다.

-L, --files-without-match
Suppress normal output; instead print the name of each input file from which no output would normally have been printed. The scanning will stop on the first match.
일반적으로 출력되는 출력을 스킵하고 각각의 입력파일을 출력한다.
처음으로 매칭되는 파일이 나타나면 중지된다.

-l, --files-with-matches
Suppress normal output; instead print the name of each input file from which output would normally have been printed. The scanning will stop on the first match.
-L 과 반대

--mmap
If possible, use the mmap(2) system call to read input, instead of the default read(2) system call. In some situations, --mmap yields better performance. However, --mmap can cause undefined behavior (including core dumps) if an input file shrinks while grep is operating, or if an I/O error occurs.
가능하면 read 시스템콜대신 입력을 읽어들이는 mmap 시스템콜을 사용한다.
이 경우, 보다나은 퍼포먼스를 유지하지만 또한, grep 작동중 입력파일이 줄어든다거나 I/O 에러가 발생하면 비정상적인 동작을 야기시키기도 한다.

-n, --line-number
Prefix each line of output with the line number within its input file.
입력파일의 해당 라인을 문두에 출력한다.

-q, --quiet, --silent
Quiet; suppress normal output. The scanning will stop on the first match. Also see the -s or --no-messages option below.
출력을 억제한다. 처음으로 매칭되는것이 발견되면 중지한다.
-s, --no-messages 옵션 참조

-r, --recursive
Read all files under each directory, recursively; this is equivalent to the -d recurse option.
하위 디렉토리를 순환적으로 모두 읽는다.
-d recurse 옵션과 동등하다.

-s, --no-messages
Suppress error messages about nonexistent or unreadable files. Portability note: unlike GNU grep, traditional grep did not conform to POSIX.2, because traditional grep lacked a -q option and its -s option behaved like GNU grep's -q option. Shell scripts intended to be portable to traditional grep should avoid both -q and -s and should redirect output to /dev/null instead.
존재하지 않거나 읽기불가능한 파일에대한 에러메세지을 출력하지 않는다.
GNU grep과는 다르게 정통 grep은 POSIX.2 규격에 부합하지 않는다. 때문에 정통 grep은 -q 옵션이나 GNU -q 옵션같은 -s 옵션의 역할이 미미하다.
쉘스크립트에선 이식성을 위해 정통 grep에서 -q, -s 옵션을 억제하거나 /dev/null로 리다이렉트 시킨다.

-U, --binary
Treat the file(s) as binary. By default, under MS-DOS and MS-Windows, grep guesses the file type by looking at the contents of the first 32KB read from the file. If grep decides the file is a text file, it strips the CR characters from the original file contents (to make regular expressions with ^ and $ work correctly). Specifying -U overrules this guesswork, causing all files to be read and passed to the matching mechanism verbatim; if the file is a text file with CR/LF pairs at the end of each line, this will cause some regular expressions to fail. This option has no effect on platforms other than MS-DOS and MS-Windows.
바이너리 파일로 취급한다.
MS-DOS나 MS-Windows에서는 grep은 기본적으로 파일의 첫 32KB의 내용을 보고 파일타입을 예측한다.
만약 grep이 텍스트파일로 인식하면 (정확한 정규표현 작업을 위해서) 원본파일로부터 CR 문자를 없앤다.
-U 옵션에 쓰이는건 모든 파일이 읽혀지고 매칭절차를 지나쳐야 하기때문이다.
각 라인의 끝에 CR/LF 가 포함된 텍스트파일이라면 정규표현식 처리에 원하지 않는 결과가 발생할 것이다. 이 옵션은 MS-DOS, MS-Windows와 다른 플랫폼에서는 작동하지 않는다.

-u, --unix-byte-offsets
Report Unix-style byte offsets. This switch causes grep to report byte offsets as if the file were Unix-style text file, i.e. with CR characters stripped off. This will produce results identical to running grep on a Unix machine. This option has no effect unless -b option is also used; it has no effect on platforms other than MS-DOS and MS-Windows.
유닉스 스타일의 바이트출력한다.
이런 변환이 있기때문에 grep이 유닉스 스타일의 텍스트파일처럼 읽기가 가능해진다.
이것은 유닉스머신에서의 grep처럼 정확한 결과를 산출할 것이다.
이 옵션은 -b 옵션이 쓰이지 않으면 소용이 없다.
MS-DOS, MS-Windows와 다른 플랫폼에서는 작동하지 않는다.

-V, --version
Print the version number of grep to standard error. This version number should be included in all bug reports (see below).
표준에러로 grep의 버전을 출력한다.
버전넘버는 모든 버그리포트를 포함한다(아래참조)

-v, --invert-match
Invert the sense of matching, to select non-matching lines.
매칭을 바꾼다. 매치되지 않은 라인을 출력한다.

-w, --word-regexp
Select only those lines containing matches that form whole words. The test is that the matching substring must either be at the beginning of the line, or preceded by a non-word constituent character. Similarly, it must be either at the end of the line or followed by a non-word constituent character. Word-constituent characters are letters, digits, and the underscore.
전체 단어유형 매칭을 포함하는 라인만 선택한다.
이 테스트는 매칭되는 문자열이 라인의 처음에 위치하거나 non-word에 의해 선두에 와야한다. 마찬가지로, 문미에 오거나 non-word가 마지막에 와야 한다.
word-constituent 는 문자,숫자,밑줄이 될 수있다.

-x, --line-regexp
Select only those matches that exactly match the whole line.
전체 라인과 정확하게 매치되는 것만 출력한다.

-y
Obsolete synonym for -i.
-i 옵션과 같음. 이제는 쓰이지 않음

-Z, --null
Output a zero byte (the ASCII NUL character) instead of the character that normally follows a file name. For example, grep -lZ outputs a zero byte after each file name instead of the usual newline. This option makes the output unambiguous, even in the presence of file names containing unusual characters like newlines. This option can be used with commands like find -print0, perl -0, sort -z, and xargs -0 to process arbitrary file names, even those that contain newline characters.
파일명 대신 0 byte 문자를 출력한다.
예를들면, grep -IZ 는 유용한 newline 문자대신 각 파일명뒤에 0byte를 출력한다.
이 옵션은 newline과 같은 유용한 캐릭터를 포함하는 파일명까지도 출력을 명쾌하게 해준다. 이 옵션은 임의의 파일명을 처리하는 find -print0, perl -0, sort -z, xargs -0과 같은 명령어와 함께 사용될 수있고 newline 캐릭터를 포함하는 그 자체로도 사용할 수있다.

REGULAR EXPRESSIONS

A regular expression is a pattern that describes a set of strings. Regular expressions are constructed analogously to arithmetic expressions, by using various operators to combine smaller expressions.

Grep understands two different versions of regular expression syntax: ``basic'' and ``extended.'' In GNU grep, there is no difference in available functionality using either syntax. In other implementations, basic regular expressions are less powerful. The following description applies to extended regular expressions; differences for basic regular expressions are summarized afterwards.

The fundamental building blocks are the regular expressions that match a single character. Most characters, including all letters and digits, are regular expressions that match themselves. Any metacharacter with special meaning may be quoted by preceding it with a backslash.

A list of characters enclosed by [ and ] matches any single character in that list; if the first character of the list is the caret ^ then it matches any character not in the list. For example, the regular expression [0123456789] matches any single digit. A range of characters may be specified by giving the first and last characters, separated by a hyphen. Finally, certain named classes of characters are predefined. Their names are self explanatory, and they are [:alnum:], [:alpha:], [:cntrl:], [:digit:], [:graph:], [:lower:], [:print:], [:punct:], [:space:], [:upper:], and [:xdigit:]. For example, [[:alnum:]] means [0-9A-Za-z], except the latter form depends upon the POSIX locale and the ASCII character encoding, whereas the former is independent of locale and character set. (Note that the brackets in these class names are part of the symbolic names, and must be included in addition to the brackets delimiting the bracket list.) Most metacharacters lose their special meaning inside lists. To include a literal ] place it first in the list. Similarly, to include a literal ^ place it anywhere but first. Finally, to include a literal - place it last.

The period . matches any single character. The symbol \w is a synonym for [[:alnum:]] and \W is a synonym for [^[:alnum]].

The caret ^ and the dollar sign $ are metacharacters that respectively match the empty string at the beginning and end of a line. The symbols \< and \> respectively match the empty string at the beginning and end of a word. The symbol \b matches the empty string at the edge of a word, and \B matches the empty string provided it's not at the edge of a word.

A regular expression may be followed by one of several repetition operators:

정규표현식은 문자열 하나의 세트를 묘사하는 패턴이다.

정규표현식은 작은 표현식들과 혼합되어진 다양한 연산자들에 의해서 산술계산식과 유사하게 이루어진다.

grep은 정규표현식의 두가지 다른 문법(기본, 확장)을 수렴한다.

GNU grep에서는 각각의 문법에 사용되는 유용한 기능들의 다른점이 거의 없다.

다른 구현에서는 기본정규표현식이 확장정규표현식보다는 약간 부족한 점이 있다.

아래는 확장정규표현식을 적용한다.

기본정규표현식과 다른점은 나중에 요약을 한다.

기본블럭은 하나의 캐릭터와 매치되는 정규표현식이다.

문자,숫자를 포함하는 대부분의 문자열들은 자신과 매치되는 정규표현식들이다.

특별한 의미를 나타내는 메타문자들은 백슬래시가 앞에와서 쿼우팅 된다.

[ 와 ] 로 둘러쌓인 문자들은 그 리스트중 하나의 문자와 매치가 된다.

만약 리스트의 첫번째 캐릭터가 캐럿(^)이면 리스트에서 매칭되지 않는 캐릭터를 찾는다.

예를들면, 정규표현식 [0123456789] 는 어떠한 한자리 숫자와도 매칭이 된다.

캐릭터의 범위는 주어진 첫번째문자와 하이픈(-)으로 분리된 마지막문자에 의해 정해진다.

마지막으로, 문자의 이름기반클래스들은 미리 정해져있다.

그들의 이름은 자의적이다.

[:alnum:], [:alpha:], [:cntrl:], [:digit:], [:graph:], [:lower:], [:print:], [:punct:], [:space:], [:upper:], [:xdigit:]...

예를들면, [[:alnum:]] 은 그 유형이 독립적이기때문에 POSIX 로케일과 ASCII 캐릭터 인코딩에 의존하는 유형이후의 것들을 제외하면 [0-9a-zA-Z]을 의미한다.

대부분의 메타문자들은 리스트안에서 그들 특유의 기능을 잃는다.

(리스트 처음에 "]"을 포함하는것, 마찬가지로 리스트의 처음이 아닌 다른곳에 "^"을 위치하는것,

결과적으로 마지막에 "-" 을 위치하는것을 포함한다.)

점(.)은 하나의 문자와 매치시킨다.

\w는 [[:alnum:]]과 같고, \W는 [^[:alnum:]]과 같다.

캐럿(^)과 달러사인($)은 각각 문장의 처음 빈 문자와 라인끝의 빈 문자와 매칭시키는 메타문자다.

\<, \>는 각각 단어의 시작과 끝을 매칭시킨다.

\b 는 단어의 테두리(처음과 끝)의 빈 문자와 매칭된다.

\B 는 단어의 테두리에 있지않는 빈 문자와 매칭된다.

아래의 몇가지 정규표현식 

?
The preceding item is optional and matched at most once.
*
The preceding item will be matched zero or more times.
+
The preceding item will be matched one or more times.
{n}
The preceding item is matched exactly n times.
{n,}
The preceding item is matched n or more times.
{n,m}
The preceding item is matched at least n times, but not more than m times.

?         하나가 매칭될때

*         0또는 그 이상과 매칭될때

+         1또는 그 이상과 매칭될때

{n}      정확하게 n번 매칭될때

{n,}     n번이나 그 이상 매칭될때

{n,m}  최소 n번에서 최대 m번까지 매칭될때


Two regular expressions may be concatenated; the resulting regular expression matches any string formed by concatenating two substrings that respectively match the concatenated subexpressions.

Two regular expressions may be joined by the infix operator |; the resulting regular expression matches any string matching either subexpression.

Repetition takes precedence over concatenation, which in turn takes precedence over alternation. A whole subexpression may be enclosed in parentheses to override these precedence rules.

The backreference \n, where n is a single digit, matches the substring previously matched by the nth parenthesized subexpression of the regular expression.

In basic regular expressions the metacharacters ?, +, {, |, (, and ) lose their special meaning; instead use the backslashed versions \?, \+, \{, \|, \(, and \).

Traditional egrep did not support the { metacharacter, and some egrep implementations support \{ instead, so portable scripts should avoid { in egrep patterns and should use [{] to match a literal {.

GNU egrep attempts to support traditional usage by assuming that { is not special if it would be the start of an invalid interval specification. For example, the shell command egrep '{1' searches for the two-character string {1 instead of reporting a syntax error in the regular expression. POSIX.2 allows this behavior as an extension, but portable scripts should avoid it.

두개의 정규표현식은 서로 연결된다.

작은 정규표현식으로 연결된 두 문자열의 연결에 의해서 어떠한 문자열형태가 매칭된 결과 정규표현식으로 나타난다.

두 정규표현식은 파이프(|) 연산자에의해 합쳐진다.

각 하부표현식중에서 매칭되는 특정한 표현식이 결과값이 된다.

각각의 연결들은 우선순위를 가지게 되고 모든 하부표현식들은 이들의 부모(원래 정규표현식)에 의해 둘러쌓여지고 그에 따른 우순순위를 가지게 된다.

backreference \n 에서 n은 하나의 숫자이다.

이전에 매칭된 하부분자열은 정규표현식의 n번째에 삽입이 삽입이 된다.

기본정규표현식에서는 메타문자(예를들면 ?,|,{,|,(,) 등등..)들이 본래의 특정의미를 잃는다.

대신 백슬래쉬와 함께 사용한다. \?, \+, \{, \}, \|, \(

전통적인 egrep은 { 메타문자를 지원하지 않는다. \{ 을 대신 사용한다.

그래서 이식성을 고려한 쉘스크립트에서는 egrep에서 { 사용을 피하거나 상수형의 { 과 매칭되는 [}] 을 사용한다.

GNU egrep 에서는 유용하지않은 기술서에서 시작된다면 { 를 특별한 의미를 부여하지않고 전통적인 사용법을 지원하려하고 있다.

예를들면, 쉘 커맨드 egrep '{1' 은 원래, POSIX.2 에서 확장을 허용하기때문에 정규표현식에서 에러를 발생시키지만 그렇게하지 않고 대신 단순히 문자열 "{1" 을 추출한다.

하지만 이식성을 고려한 쉘스크립트에서 이러한 방식은 피해야 한다.

ENVIRONMENT VARIABLES

GREP_OPTIONS
This variable specifies default options to be placed in front of any explicit options. For example, if GREP_OPTIONS is '--binary-files=without-match --directories=skip', grep behaves as if the two options --binary-files=without-match and --directories=skip had been specified before any explicit options. Option specifications are separated by whitespace. A backslash escapes the next character, so it can be used to specify an option containing whitespace or a backslash.
LC_ALL, LC_MESSAGES, LANG
These variables specify the LC_MESSAGES locale, which determines the language that grep uses for messages. The locale is determined by the first of these variables that is set. American English is used if none of these environment variables are set, or if the message catalog is not installed, or if grep was not compiled with national language support (NLS).
LC_ALL, LC_CTYPE, LANG
These variables specify the LC_CTYPE locale, which determines the type of characters, e.g., which characters are whitespace. The locale is determined by the first of these variables that is set. The POSIX locale is used if none of these environment variables are set, or if the locale catalog is not installed, or if grep was not compiled with national language support (NLS).
POSIXLY_CORRECT
If set, grep behaves as POSIX.2 requires; otherwise, grep behaves more like other GNU programs. POSIX.2 requires that options that follow file names must be treated as file names; by default, such options are permuted to the front of the operand list and are treated as options. Also, POSIX.2 requires that unrecognized options be diagnosed as ``illegal'', but since they are not really against the law the default is to diagnose them as ``invalid''. POSIXLY_CORRECT also disables _N_GNU_nonoption_argv_flags_, described below.
_N_GNU_nonoption_argv_flags_
(Here N is grep's numeric process ID.) If the ith character of this environment variable's value is 1, do not consider the ith operand of grep to be an option, even if it appears to be one. A shell can put this variable in the environment for each command it runs, specifying which operands are the results of file name wildcard expansion and therefore should not be treated as options. This behavior is available only with the GNU C library, and only when POSIXLY_CORRECT is not set.

DIAGNOSTICS

Normally, exit status is 0 if matches were found, and 1 if no matches were found. (The -v option inverts the sense of the exit status.) Exit status is 2 if there were syntax errors in the pattern, inaccessible input files, or other system errors.

일반적으로 매칭된것이 있으면 종료값은 0이다.

매칭값이 없으면 1(-v 옵션은 반대로 생각해야한다)

만약, 패턴에서 문법에러가 발생하거나, 접근불가능한 입력파일 또는 다른 시스템에러가 발생하면 종료값 2를 반환한다.

BUGS

Email bug reports to bug-gnu-utils@gnu.org. Be sure to include the word ``grep'' somewhere in the ``Subject:'' field.

Large repetition counts in the {m,n} construct may cause grep to use lots of memory. In addition, certain other obscure regular expressions require exponential time and space, and may cause grep to run out of memory.

Backreferences are very slow, and may require exponential time.