9/16/2015

[DEBIAN] grep -v , -E 옵션을 이용한 문자열 제외하여 찾기(grep to exclude a specific string)



데이터 검색, 각종 명령어 사용 시 많이 사용되는 Function 인 grep에 관한 이야기를 할까 합니다.
대부분 grep을 찾아야할 문자열을 찾기 위해 많이 사용하는데, 제외하고 볼 문자열로는 아시는분도 있고 모르시는분도 있고 그런 것 같습니다.

간단하게 grep 의 제외하기 기능 옵션을 사용하는 방법입니다.

# grep --help
사용법: grep [옵션]... 패턴 [파일]...
...snip...

정규식 선택과 해석
  -E, --extended-regexp     확장된 정규 표현식으로 된 패턴 (ERE)

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

grep 의 help 로 확인할 수 있는 옵션 중 제외를 위해 사용할 옵션은 v 옵션입니다. (대문자는 Version을 뜻해요)

 -v, --invert-match 설명대로 매칭되지 않은 line 을 출력할 때 사용하는 옵션입니다.

grep -v, -E 옵션을 활용한 매칭 문자열 제외


직접 테스트하며 기능에 대해 알아보겠습니다.

# ll
합계 12
-rwsrwxrwx  1 root root    0  9월 15 17:23 4777_abc
-rwsrwxrwx  1 root root    0  9월 15 17:23 4777_cba

4777_abc와 4777_cba 두개의 파일을 생성해두었습니다.
검색을 위해 위험한 권한인 4777로 세팅하였습니다.

아래와 같이 퍼미션이 4777인 파일만 검색하면 abc,cba 모두 출력됩니다.
# find ./* -perm 4777
./4777_abc
./4777_cba

일반적으로 문자열을 선택에서 출력하는 grep 의 경우 아래와 같이 하면 의도한 값(abc)만 나오게 되지요.
# find ./* -perm 4777 | grep "abc"
./4777_abc

여기서 -v 옵션을 이용하여 abc를 제외하고 검색하면 cba만 나타나게 됩니다.
# find ./* -perm 4777 | grep -v "abc"
./4777_cba

여기서 위에 메뉴얼에 있던 -E, --extended-regexp  확장된 정규 표현식으로 된 패턴 (ERE) 이 옵션을 사용하면
규칙을 쉽게 많이 걸어 사용이 가능합니다.

테스트를 위해 파일을 더 추가하였습니다.
# ll
합계 12
-rwsrwxrwx  1 root root    0  9월 15 17:23 4777_abc
-rwsrwxrwx  1 root root    0  9월 15 17:23 4777_cba
-rwsrwxrwx  1 root root    0  9월 15 17:30 4777_zzza
-rwsrwxrwx  1 root root    0  9월 15 17:30 4777_zzzc
-rwsrwxrwx  1 root root    0  9월 15 17:30 4777_zzze
-rwsrwxrwx  1 root root    0  9월 15 17:30 4777_zzzh
-rwsrwxrwx  1 root root    0  9월 15 17:30 4777_zzzq
-rwsrwxrwx  1 root root    0  9월 15 17:30 4777_zzzs
-rwsrwxrwx  1 root root    0  9월 15 17:30 4777_zzzz

여기서 -E(정규식) 옵션을 이용해 abc와 zzzz, zzzh 문자열이 제외된 값만 검색합니다.
# find ./* -perm 4777 | grep -Ev 'abc|zzzh|zzzz'
./4777_cba
./4777_zzza
./4777_zzzc
./4777_zzze
./4777_zzzq
./4777_zzzs

Grep Options



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                deprecated no-op; evokes a warning

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 file name for each match
  -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 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, --recursive           like --directories=recurse
  -R, --dereference-recursive  likewise, but follow all symlinks
      --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/Windows)
  -u, --unix-byte-offsets   report offsets as if CRs were not there
                            (MSDOS/Windows)





HAHWUL

Security engineer, Gopher and H4cker!

Share: | Coffee Me:

0 개의 댓글:

Post a Comment