====== grep ====== * [[:regex|RegEx]] ===== 특정 파일명에서 문자열 찾기 ===== # 현재 디렉토리 파일 한정 grep * [[http://www.cyberciti.biz/faq/unix-linux-grep-include-file-pattern-recursive-example/|grep include file pattern recursive example]] * [[https://www.cyberciti.biz/faq/grep-regular-expressions/|Regular expressions in grep ( regex ) with examples - nixCraft]] # 하위 디렉토리를 포함하려면 -r --include=GLOB 을 사용 # grep -r --include=GLOB "pattern" /path/to/dir grep -r --include="*.txt" "pattern" /path/to/dir grep -r --include="*.txt" "foo" ~/projects/ # 모든 파일 검색하고 줄번호도 함께 출력 grep -rn "pattern" /path/to/dir/* # * 가 없으면 /path/to/dir/그하위dir들 에 있는 파일만 검색한다. # /path/to/dir/ 바로 아래의 파일은 탐색하지 않는다. grep -rn "pattern" /path/to/dir/ # -R 은 -r 과 같으나 모든 심볼릭 링크를 따라간다. * ''xargs'' 사용 find . -name "*.java" | xargs grep "Some code to find" * ''findtext'' #!/bin/sh # findtext "검색어" "파일명" find . -name "$2" | xargs grep -Hni "$1" * ''i'' : 대소문자 구분안하기 * ''H'' : 파일명 출력 * ''n'' : 줄번호 출력 ===== 매칭되는 줄 위아래 보여주기 ===== * ''-A [줄수]'' : 매칭 되는 라인의 아래로 줄 수만큼 더 보여줌 * ''-B [줄수]'' : 매칭 되는 라인의 위로 줄 수만큼 더 보여줌 * ''-C [줄수]'' : ''-A''와 ''-B'' 둘 다 적용 ===== 정규표현식 / Regex/ Pattern 옵션 ===== * ''%%-E, --extended-regexp%%'' : ''egrep'' 명령과 동일. 확장정규표현식. 이걸 써야 정규표현식이 좀 더 자유로웠음. 이걸 안 사용하면 정규표현식 특수문자를 ''\'' 로 계속해서 escape 시켜줘야함. * ''%%-F, --fixed-strings%% : 패턴이 아닌 고정 문자열로 검색. 정규표현식의 특수문자 자체를 검색할 때는 이게 편함. * ''%%-G, --basic-regexp%% : 기본값. 기본 정규 표현식. * [[https://linuxize.com/post/regular-expressions-in-grep/|Regular Expressions in Grep (Regex) | Linuxize]] * ''%-o PATTERN'' : 패턴에 매칭된 문자열만 뽑아준다(한줄 전체 말고). * ''-i'' : 정규 표현식에서도 대소문자 구분안함. ===== 여러 단어 검색 ===== * [[https://www.cyberciti.biz/faq/searching-multiple-words-string-using-grep/|Search Multiple Words / String Pattern Using grep Command on Bash shell - nixCraft]] grep 'word1\|word2\|word3' /path/to/file ### Search all text files ### grep 'word*' *.txt ### Search all python files for 'wordA' or 'wordB' ### grep 'wordA*'\''wordB' *.py grep -E 'word1|word2' *.doc grep -e string1 -e string2 *.pl egrep "word1|word2" *.c ===== 기타 옵션 ===== * ''-l'' : 매칭되는 문자열이 있는 파일 목록만 보여줌 * ''%%--%%color=auto'' : 찾은 문자열에 색깔을 입힌다. [[linux:ubuntu|Ubuntu Linux]]에는 ''grep --color=auto''가 기본 alias 로 걸려있다. ===== grep 대체 ===== * [[linux:ack|ack - beyond grep]] * [[linux:silver_searcher|The Silver Searcher - ag]] * [[https://github.com/ggreer/the_silver_searcher|The silver searcher]] * [[https://github.com/monochromegane/the_platinum_searcher|The Platinum searcher]] * [[http://betterthanack.com/|Better Than Ack]]