티스토리 뷰

IT지식

grep 명령에 사용

민자르 2018. 4. 30. 11:28
반응형

grep 명령어는 자주 사용되지만 자세한 기능에 대해서는 몰라서 정리를 해둔다.


grep : 파일 전체를 뒤져 정규표현식에 대응하는 모든 행들을 출력한다.(이것만 주로 사용)

egrep : grep의 확장판으로, 추가 정규표현식 메타문자들을 지원한다.

fgrep : fixed grep 이나 fast grep으로 불리며, 모든 문자를 문자 그래도 취급한다. 즉, 정규표현식의 메타문자도 일반 문자로 취급한다.


위 명령어 중 grep 말고는 사용해본적이 없다. 하지만 언젠가 다른 명령어도 사용해야 될때가 올 것 같다.

그래도 지금 나에게 필요한 기능만 정리해두고 나머지는 다음에 필요할때 정리하겠다.



grep [-옵션] 정규표현식 파일


정규표현식에 들어 가는 예시

메타문자
기    능
사용 예
사용 예 설명
^
행의 시작 지시자
'^love'
love로 시작하는 모든 행과 대응
$
행의 끝 지시자
'love$'
love로 끝나는 모든 행과 대응
.
하나의 문자와 대응
'l..e'
l 다음에 두 글자가 나오고 e로 끝나는 문자열을 포함하는 행과 대응
*
선행문자와 같은 문자의 0개 혹은 임의개수와 대응
' *love'
0개 혹은 임의 개수의 공백 문자 후에 love로 끝나는 문자열을 포함한 행과 대응
[]
[] 사이의 문자 집합중 하나와 대응
'[Ll]ove'
love나 Love를 포함하는 행과 대응
[^ ]
문자집합에 속하지 않는 한 문자와 대응
'[^A-K]love'
A와 K 사이의 범위에 포함되지 않는 한 문자와 ove가 붙어있는 문자열과 대응
\<
단어의 시작 지시자
'\
love로 시작하는 단어를 포함하는 행과 대응(vi,grep에서 지원)
\>
단어의 끝 지시자
'love\>'
love로 끝나는 단어를 포함하는 행과 대응
(vi,grep에서 지원)
\(..\)
다음 사용을 위해 태그를 붙인다.
'\(lov\)ing'
지정된 부분을 태크1에 저장한다. 나중에 태그값을 참고하려면 \1을 쓴다. 맨 왼쪽부터 시작해 태그를 9개가지 쓸 수 있다. 왼쪽 예에서는 lov가 레지스터1에 저장되고 나중에 \1로 참고할 수 있다.
x\{m\}
문자 x를 m번 반복한다.
'o\{5\}'
문자 o가 5회 연속적으로 나오는 모든 행과 대응
x\{m,\}
적어도 m번 반복한다.
'o\{5,\}'
문자 o가 최소한 5회 반복되는 모든 행과 대응
x\{m,n\}
m회 이상 n회 이하 반복한다.
o\{5,10\}'
문자 o가 5회에서 10회 사이의 횟수로 연속적으로 나타나는 문자열과 대응


옵션에 들어 가는 예시

옵션
동작 설명
-b
검색 결과의 각 행 앞에 검색된 위치의 블록 번호를 표시한다. 검색 내용이 디스크의 어디쯤 있는지 위치를 알아내는데 유용하다.
-c
검색 결과를 출력하는 대신, 찾아낸 행의 총수를 출력한다.  (count)
-h
파일 이름을 출력하지 않는다.
-i
대소문자를 구분 하지 않는다.(대문자와 소문자를 동일하게 취급). (ignore)
-l
패턴이 존재하는 파일의 이름만 출력한다.(개행문자로 구분) (list file)
-n
파일 내에서 행 번호를 함께 출력한다. (number)
-s
에러 메시지 외에는 출력하지 않는다. 종료상태를 검사할 때 유용하게 쓸 수 있다.
-v
패턴이 존재하지 않는 행만 출력한다. (invert)
-w
패턴 표현식을 하나의 단어로 취급하여 검색한다. (word)



위에 있는 내용으로 예제를 만들어 보자


$ grep -n 'debug' *

-> 현재 디렉토리의 모든 파일에서 'debug'라는 패턴이 들어간 문자열과 행번호 출력


$ grep -v 'debug' main.cpp

-> main.cpp 파일에서 'debug'라는 패턴이 들어가지 않은 행을 출력(거의 사용하지 않음)


$ grep -r 'debug' * 

-> 현재 디렉토리의 및 서브디렉토리 모든 파일에서 'debug'라는 패턴이 들어간 문자열 출력


$ grep --help

-> 이제 도움말을 보면 알 수 있을 것이다. 검색해서 찾지 말고 도움말 보고 하자.


사용법: grep [옵션]... 패턴 [파일]...

Search for PATTERN in each FILE or standard input.

PATTERN is, by default, a basic regular expression (BRE).

Example: grep -i 'hello world' menu.h main.c


Regexp selection and interpretation:

  -E, --extended-regexp     PATTERN is an extended regular expression (ERE)

  -F, --fixed-strings       PATTERN is a set of newline-separated fixed strings

  -G, --basic-regexp        PATTERN is a basic regular expression (BRE)

  -P, --perl-regexp         PATTERN is a Perl regular expression

  -e, --regexp=PATTERN      use PATTERN for matching

  -f, --file=FILE           obtain PATTERN from FILE

  -i, --ignore-case         ignore case distinctions

  -w, --word-regexp         force PATTERN to match only whole words

  -x, --line-regexp         force PATTERN to 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             print version information and exit

      --help                display this help and exit

      --mmap                ignored for backwards compatibility


Output control:

  -m, --max-count=NUM       stop after NUM matches

  -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 the filename for each match

  -h, --no-filename         suppress the prefixing filename on output

      --label=LABEL         print LABEL as filename for standard input

  -o, --only-matching       show only the part of a line matching PATTERN

  -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, -r, --recursive       equivalent to --directories=recurse

      --include=FILE_PATTERN  search only files that match FILE_PATTERN

      --exclude=FILE_PATTERN  skip files and directories matching FILE_PATTERN

      --exclude-from=FILE   skip files matching any file pattern from FILE

      --exclude-dir=PATTERN  directories that match PATTERN will be skipped.

  -L, --files-without-match  print only names of FILEs containing no match

  -l, --files-with-matches  print only names of FILEs containing matches

  -c, --count               print only a count of matching 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

      --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)

  -u, --unix-byte-offsets   report offsets as if CRs were not there (MSDOS)


`egrep' means `grep -E'.  `fgrep' means `grep -F'.

Direct invocation as either `egrep' or `fgrep' is deprecated.

With no FILE, or when FILE is -, read standard input.  If less than two FILEs

are given, assume -h.  Exit status is 0 if any line was selected, 1 otherwise;

if any error occurs and -q was not given, the exit status is 2.


Report bugs to: bug-grep@gnu.org

GNU Grep home page: <http://www.gnu.org/software/grep/>

General help using GNU software: <http://www.gnu.org/gethelp/>


728x90
반응형
댓글