your programing

특정 파일을 통해 grep하지 않으려면 grep --exclude /-include 구문을 사용하십시오.

lovepro 2020. 9. 29. 08:17
반응형

특정 파일을 통해 grep하지 않으려면 grep --exclude /-include 구문을 사용하십시오.


foo=디렉토리 트리의 텍스트 파일에서 문자열 찾고 있습니다. 일반적인 Linux 컴퓨터에 있으며 bash 셸이 있습니다.

grep -ircl "foo=" *

디렉토리에는 "foo ="와 일치하는 많은 바이너리 파일도 있습니다. 이러한 결과는 관련성이없고 검색 속도가 느리기 때문에 grep이 이러한 파일 (대부분 JPEG 및 PNG 이미지) 검색을 건너 뛰기를 원합니다. 어떻게할까요?

--exclude=PATTERN--include=PATTERN옵션 이 있다는 것을 알고 있지만 패턴 형식은 무엇입니까? grep의 man 페이지는 다음과 같이 말합니다.

--include=PATTERN     Recurse in directories only searching file matching PATTERN.
--exclude=PATTERN     Recurse in directories skip file matching PATTERN.

grep include , grep include exclude , grep exclude 및 변형 검색에서 관련 항목을 찾지 못했습니다.

특정 파일에서만 grepping하는 더 좋은 방법이 있다면, 저는 그게 전부입니다. 문제가되는 파일을 이동하는 것은 옵션이 아닙니다. 특정 디렉토리 만 검색 할 수 없습니다 (디렉토리 구조는 모든 곳에서 모든 것이 엉망이됩니다). 또한 아무것도 설치할 수 없으므로 일반적인 도구 (예 : grep 또는 제안 된 찾기 )를 사용해야 합니다 .


쉘 글 로빙 구문을 사용하십시오.

grep pattern -r --include=\*.{cpp,h} rootdir

의 구문 --exclude은 동일합니다.

별표는 셸에 의해 확장되는 것을 방지하기 위해 백 슬래시로 이스케이프됩니다 (예 : 따옴표도 마찬가지로 --include="*.{cpp,h}"작동 함). 그렇지 않고 현재 작업 디렉토리에 패턴과 일치하는 파일이있는 경우 명령 줄은 grep pattern -r --include=foo.cpp --include=bar.h rootdir라는 이름으로 확장되어 foo.cppand 라는 파일 만 검색합니다 bar.h.


바이너리 파일을 건너 뛰고 싶다면 -I(대문자 i) 옵션 을 살펴 보는 것이 좋습니다 . 바이너리 파일을 무시합니다. 정기적으로 다음 명령을 사용합니다.

grep -rI --exclude-dir="\.svn" "pattern" *

재귀 적으로 검색하고 바이너리 파일을 무시하며 내가 원하는 패턴에 대해 Subversion 숨겨진 폴더 내부를 보지 않습니다. 직장에서 내 상자에 "grepsvn"이라는 별칭이 있습니다.


정확히 이러한 상황을 위해 설계된 ack를 살펴보십시오 . 귀하의 예

grep -ircl --exclude=*.{png,jpg} "foo=" *

ack로 완료됩니다.

ack -icl "foo="

ack는 기본적으로 바이너리 파일을 찾지 않고 -r이 기본적으로 켜져 있기 때문입니다. CPP 및 H 파일 만 원하면

ack -icl --cpp "foo="

grep 2.5.3은 원하는 방식으로 작동하는 --exclude-dir 매개 변수를 도입했습니다.

grep -rI --exclude-dir=\.svn PATTERN .

환경 변수를 설정할 수도 있습니다. GREP_OPTIONS = "-exclude-dir = .svn"

나는 두 번째거야 앤디 에 대한 투표 ACK는 하지만, 그것은 가장 좋습니다.


오랜만에 이것을 발견했으며 다음과 같이 여러 포함 및 제외를 추가 할 수 있습니다.

grep "z-index" . --include=*.js --exclude=*js/lib/* --exclude=*.min.js

제안 된 명령 :

grep -Ir --exclude="*\.svn*" "pattern" *

--exclude는 기본 이름에서 작동하기 때문에 개념적으로 잘못되었습니다. 즉, 현재 디렉토리에서 .svn 만 건너 뜁니다.


grep 2.5.1에서는 ~ / .bashrc 또는 ~ / .bash 프로필에이 줄을 추가해야합니다.

export GREP_OPTIONS="--exclude=\*.svn\*"

grepping grep의 출력이 때때로 매우 유용하다는 것을 알았습니다.

grep -rn "foo=" . | grep -v "Binary file"

그러나 이것이 실제로 바이너리 파일 검색을 중지하지는 않습니다.


CentOS 6.6 / Grep 2.6.3에서는 다음과 같이 사용해야합니다.

grep "term" -Hnir --include \*.php --exclude-dir "*excluded_dir*"

(그렇지 않으면 "="등호의 부족을 주목 --include, --exclude, include-dir그리고 --exclude-dir무시됩니다)


을 사용하는 것을 싫어하지 않는다면 find-prune기능이 마음에 듭니다.


find [directory] \
        -name "pattern_to_exclude" -prune \
     -o -name "another_pattern_to_exclude" -prune \
     -o -name "pattern_to_INCLUDE" -print0 \
| xargs -0 -I FILENAME grep -IR "pattern" FILENAME

첫 번째 줄에서 검색 할 디렉터리를 지정합니다. .예를 들어 (현재 디렉토리)는 유효한 경로입니다.

2 층과 3 선, 사용에 "*.png", "*.gif", "*.jpg", 등. -o -name "..." -prune패턴이있는만큼 이러한 구성을 사용하십시오 .

On the 4th line, you need another -o (it specifies "or" to find), the patterns you DO want, and you need either a -print or -print0 at the end of it. If you just want "everything else" that remains after pruning the *.gif, *.png, etc. images, then use -o -print0 and you're done with the 4th line.

Finally, on the 5th line is the pipe to xargs which takes each of those resulting files and stores them in a variable FILENAME. It then passes grep the -IR flags, the "pattern", and then FILENAME is expanded by xargs to become that list of filenames found by find.

For your particular question, the statement may look something like:


find . \
     -name "*.png" -prune \
     -o -name "*.gif" -prune \
     -o -name "*.svn" -prune \
     -o -print0 | xargs -0 -I FILES grep -IR "foo=" FILES


I'm a dilettante, granted, but here's how my ~/.bash_profile looks:

export GREP_OPTIONS="-orl --exclude-dir=.svn --exclude-dir=.cache --color=auto" GREP_COLOR='1;32'

Note that to exclude two directories, I had to use --exclude-dir twice.


git grep

Use git grep which is optimized for performance and aims to search through certain files.

By default it ignores binary files and it is honoring your .gitignore. If you're not working with Git structure, you can still use it by passing --no-index.

Example syntax:

git grep --no-index "some_pattern"

For more examples, see:


Try this one:

 $ find . -name "*.txt" -type f -print | xargs file | grep "foo=" | cut -d: -f1

Founded here: http://www.unix.com/shell-programming-scripting/42573-search-files-excluding-binary-files.html


If you search non-recursively you can use glop patterns to match the filenames.

grep "foo" *.{html,txt}

includes html and txt. It searches in the current directory only.

To search in the subdirectories:

   grep "foo" */*.{html,txt}

In the subsubdirectories:

   grep "foo" */*/*.{html,txt}

In the directories are also many binary files. I can't search only certain directories (the directory structure is a big mess). Is there's a better way of grepping only in certain files?

ripgrep

This is one of the quickest tools designed to recursively search your current directory. It is written in Rust, built on top of Rust's regex engine for maximum efficiency. Check the detailed analysis here.

So you can just run:

rg "some_pattern"

It respect your .gitignore and automatically skip hidden files/directories and binary files.

You can still customize include or exclude files and directories using -g/--glob. Globbing rules match .gitignore globs. Check man rg for help.

For more examples, see: How to exclude some files not matching certain extensions with grep?

On macOS, you can install via brew install ripgrep.


find and xargs are your friends. Use them to filter the file list rather than grep's --exclude

Try something like

find . -not -name '*.png' -o -type f -print | xargs grep -icl "foo="

those scripts don't accomplish all the problem...Try this better:

du -ha | grep -i -o "\./.*" | grep -v "\.svn\|another_file\|another_folder" | xargs grep -i -n "$1"

this script is so better, because it uses "real" regular expressions to avoid directories from search. just separate folder or file names with "\|" on the grep -v

enjoy it! found on my linux shell! XD


Look @ this one.

grep --exclude="*\.svn*" -rn "foo=" * | grep -v Binary | grep -v tags

The --binary-files=without-match option to GNU grep gets it to skip binary files. (Equivalent to the -I switch mentioned elsewhere.)

(This might require a recent version of grep; 2.5.3 has it, at least.)


suitable for tcsh .alias file:

alias gisrc 'grep -I -r -i --exclude="*\.svn*" --include="*\."{mm,m,h,cc,c} \!* *'

Took me a while to figure out that the {mm,m,h,cc,c} portion should NOT be inside quotes. ~Keith


To ignore all binary results from grep

grep -Ri "pattern" * | awk '{if($1 != "Binary") print $0}'

The awk part will filter out all the Binary file foo matches lines


Try this:

  1. Create a folder named "--F" under currdir ..(or link another folder there renamed to "--F" ie double-minus-F.
  2. #> grep -i --exclude-dir="\-\-F" "pattern" *

참고URL : https://stackoverflow.com/questions/221921/use-grep-exclude-include-syntax-to-not-grep-through-certain-files

반응형