etc./StackOverFlow

find 에서 디렉토리를 제외하는 방법. 명령

청렴결백한 만능 재주꾼 2022. 1. 6. 11:11
반응형

질문자 :helion3


find 명령을 실행하려고 하는데 특정 디렉토리를 어떻게 제외합니까?

다음은 우리가 사용 find

 for file in $(find . -name '*.js') do java -jar config/yuicompressor-2.4.2.jar --type js $file -o $file done


-prune 이 작동하지 않으면 다음을 수행합니다.

 find -name "*.js" -not -path "./directory/*"

주의 사항: 원하지 않는 모든 디렉토리를 탐색해야 합니다.


GetFree

-prune 스위치를 사용합니다. 예를 들어, misc 디렉토리를 제외하려면 find 명령에 -path ./misc -prune -o 를 추가하기만 하면 됩니다.

 find . -path ./misc -prune -false -o -name '*.txt'

다음은 여러 디렉토리가 있는 예입니다.

 find . -type d \( -path dir1 -o -path dir2 -o -path dir3 \) -prune -false -o -name '*.txt'

여기서 우리는 현재 디렉토리에서 ./dir1 , ./dir2./dir3 find 표현식에서 기준 -path dir1 -o -path dir2 -o -path dir3 ( dir1 또는 dir2인 경우 또는 dir3 type -d 과 AND 연결됩니다.

모든 수준에서 디렉토리 이름을 제외하려면 -name 사용하십시오.

 find . -type d \( -name node_modules -o -name dir2 -o -path name \) -prune -false -o -name '*.json'

f10bit

다른 제안된 솔루션보다 다음을 추론하기가 더 쉽습니다.

 find build -not \( -path build/external -prune \) -name \*.js # you can also exclude multiple paths find build -not \( -path build/external -prune \) -not \( -path build/blog -prune \) -name \*.js

중요 참고 사항: -path 다음에 입력하는 경로 find 가 제외 없이 인쇄되는 것과 정확히 일치해야 합니다. 이 문장이 혼란스럽다면 다음과 같이 전체 find /full/path/ -not \( -path /full/path/exclude/this -prune \) ... . 더 나은 이해를 원하시면 참고 [1]을 참조하십시오.

\(\) 내부에는 build/external 와 정확히 일치하는 표현식이 있으며(위의 중요 참고 사항 참조) 성공하면 아래 항목을 통과하지 않습니다. 이것은 다음 탈출 괄호와 하나의 표현으로 그룹화하고,로 시작되는 -notfind 그 표현에 의해 일치 된 아무것도를 건너 뜁니다.

-not 을 추가 -prune 숨긴 다른 모든 파일이 다시 나타나지 않는지 물을 수 있으며 대답은 아니오입니다. -prune 작동하는 방식은 일단 도달하면 해당 디렉토리 아래의 파일이 영구적으로 무시된다는 것입니다.

이것은 실제 사용 사례에서 나온 것인데, Wintersmith가 생성한 일부 파일에 대해 yui-compressor를 호출해야 했지만 그대로 보내야 하는 다른 파일은 제외했습니다.


참고 [1] /tmp/foo/bar 를 제외 find /tmp \(... "와 같이 find를 실행 -path /tmp/foo/bar 지정해야 합니다. 반면에 다음과 같이 find 를 실행하십시오 cd /tmp; find . \(... -path ./foo/bar 를 지정해야 합니다.


Daniel C. Sobral

디렉토리를 건너뛸 때 선호되는 구문이 무엇인지에 대해 분명히 혼란이 있습니다.

GNU 의견

 To ignore a directory and the files under it, use -prune

GNU 찾기 매뉴얼 페이지에서

추리

-prune find 가 디렉토리로 내려가는 것을 중지합니다. -not -path 를 지정하면 여전히 건너뛴 디렉토리 -not -path find 각 파일을 테스트할 때마다 false가 됩니다.

-prune 관련 문제

-prune 은 의도한 대로 수행하지만 여전히 사용할 때 주의해야 할 사항이 있습니다.

  1. find 는 정리된 디렉토리를 인쇄합니다.

    • TRUE 이는 의도된 동작으로, 해당 동작에 적용되지 않습니다. 디렉토리를 모두 인쇄하지 않으려면 논리적으로 디렉토리를 생략하는 구문을 사용하십시오.
  2. -prune -print 와 함께만 작동하고 다른 작업은 수행하지 않습니다.

    • 사실이 아닙니다 . -prune -delete 제외한 모든 작업과 함께 작동합니다. 삭제와 함께 작동하지 않는 이유는 무엇입니까? -delete 가 작동하려면 find가 DFS 순서로 디렉토리를 탐색해야 합니다. -delete 가 먼저 잎을 삭제한 다음 잎의 부모 등을 삭제 -prune 을 지정하는 것이 의미가 find 를 눌러야 합니다 -depth 또는 -delete 를 켜면 분명히 의미가 없는 디렉토리 내림차순을 중지합니다.

성능

나는 이 질문에 대한 세 가지 상위 투표 답변에 대한 간단한 테스트를 설정했습니다( -print-exec bash -c 'echo $0' {} \; 로 대체하여 다른 작업 예를 보여줌). 결과는 아래와 같습니다

 ---------------------------------------------- # of files/dirs in level one directories .performance_test/prune_me 702702 .performance_test/other 2 ---------------------------------------------- > find ".performance_test" -path ".performance_test/prune_me" -prune -o -exec bash -c 'echo "$0"' {} \; .performance_test .performance_test/other .performance_test/other/foo [# of files] 3 [Runtime(ns)] 23513814 > find ".performance_test" -not \( -path ".performance_test/prune_me" -prune \) -exec bash -c 'echo "$0"' {} \; .performance_test .performance_test/other .performance_test/other/foo [# of files] 3 [Runtime(ns)] 10670141 > find ".performance_test" -not -path ".performance_test/prune_me*" -exec bash -c 'echo "$0"' {} \; .performance_test .performance_test/other .performance_test/other/foo [# of files] 3 [Runtime(ns)] 864843145

결론

f10bit의 구문Daniel C. Sobral의 구문 은 모두 평균적으로 실행하는 데 10-25ms가 걸렸습니다. -prune 사용하지 않는 GetFree의 구문 은 865ms가 걸렸습니다. 예, 이것은 다소 극단적인 예이지만 런타임에 관심이 있고 원격으로 집중적인 작업을 수행하는 경우 -prune 을 사용해야 합니다.

참고 Daniel C. Sobral의 구문 -prune 구문 중 더 나은 성능을 보였습니다. 그러나 두 개의 실행 순서를 전환하면 반대 결과가 나오는 반면 정리되지 않은 버전은 항상 가장 느렸기 때문에 이것이 일부 캐싱의 결과라고 강력히 의심합니다.

테스트 스크립트

 #!/bin/bash dir='.performance_test' setup() { mkdir "$dir" || exit 1 mkdir -p "$dir/prune_me/a/b/c/d/e/f/g/h/i/j/k/l/m/n/o/p/q/r/s/t/u/w/x/y/z" \ "$dir/other" find "$dir/prune_me" -depth -type d -exec mkdir '{}'/{A..Z} \; find "$dir/prune_me" -type d -exec touch '{}'/{1..1000} \; touch "$dir/other/foo" } cleanup() { rm -rf "$dir" } stats() { for file in "$dir"/*; do if [[ -d "$file" ]]; then count=$(find "$file" | wc -l) printf "%-30s %-10s\n" "$file" "$count" fi done } name1() { find "$dir" -path "$dir/prune_me" -prune -o -exec bash -c 'echo "$0"' {} \; } name2() { find "$dir" -not \( -path "$dir/prune_me" -prune \) -exec bash -c 'echo "$0"' {} \; } name3() { find "$dir" -not -path "$dir/prune_me*" -exec bash -c 'echo "$0"' {} \; } printf "Setting up test files...\n\n" setup echo "----------------------------------------------" echo "# of files/dirs in level one directories" stats | sort -k 2 -n -r echo "----------------------------------------------" printf "\nRunning performance test...\n\n" echo \> find \""$dir"\" -path \""$dir/prune_me"\" -prune -o -exec bash -c \'echo \"\$0\"\' {} \\\; name1 s=$(date +%s%N) name1_num=$(name1 | wc -l) e=$(date +%s%N) name1_perf=$((es)) printf " [# of files] $name1_num [Runtime(ns)] $name1_perf\n\n" echo \> find \""$dir"\" -not \\\( -path \""$dir/prune_me"\" -prune \\\) -exec bash -c \'echo \"\$0\"\' {} \\\; name2 s=$(date +%s%N) name2_num=$(name2 | wc -l) e=$(date +%s%N) name2_perf=$((es)) printf " [# of files] $name2_num [Runtime(ns)] $name2_perf\n\n" echo \> find \""$dir"\" -not -path \""$dir/prune_me*"\" -exec bash -c \'echo \"\$0\"\' {} \\\; name3 s=$(date +%s%N) name3_num=$(name3 | wc -l) e=$(date +%s%N) name3_perf=$((es)) printf " [# of files] $name3_num [Runtime(ns)] $name3_perf\n\n" echo "Cleaning up test files..." cleanup

Reinstate Monica Please

이것은 나를 위해 일한 유일한 것입니다.

 find / -name MyFile ! -path '*/Directory/*'

"Directory"를 제외한 "MyFile"을 검색합니다. 별을 강조하십시오 * .


DimiDak

한 가지 옵션은 grep을 사용하여 디렉토리 이름을 포함하는 모든 결과를 제외하는 것입니다. 예를 들어:

 find . -name '*.js' | grep -v excludeddir

Joshua

-not 표기법을 선호합니다 ... 더 읽기 쉽습니다.

 find . -name '*.js' -and -not -path directory

mpapis

-prune 옵션을 사용합니다. 그래서, 다음과 같은 것:

 find . -type d -name proc -prune -o -name '*.js'

'-type d -name proc -prune'은 제외할 proc이라는 디렉터리만 찾습니다.
'-o'는 'OR' 연산자입니다.


Drew Frezell

-prune 확실히 작동하며 제외하려는 디렉토리로 내려가는 것을 방지하기 때문에 최선의 대답입니다. -not -path 는 여전히 제외된 디렉토리를 검색하지만 결과를 인쇄하지 않습니다. 제외된 디렉토리가 마운트된 네트워크 볼륨이거나 권한이 없는 경우 문제가 될 수 있습니다.

까다로운 부분은 find 가 인수의 순서에 대해 매우 구체적이어서 인수를 올바르게 이해하지 못하면 명령이 작동하지 않을 수 있다는 것입니다. 인수의 순서는 일반적으로 다음과 같습니다.

 find {path} {options} {action}

{path} : 경로와 관련된 모든 인수를 먼저 배치합니다(예: . -path './dir1' -prune -o

{options} : 이 그룹의 마지막 옵션으로 -name, -iname, etc 을 넣을 때 가장 성공적입니다. 예를 들어 -type f -iname '*.js'

{action} -prune 사용할 때 -print 를 추가하고 싶을 것입니다.

작동 예는 다음과 같습니다.

 # setup test mkdir dir1 dir2 dir3 touch dir1/file.txt; touch dir1/file.js touch dir2/file.txt; touch dir2/file.js touch dir3/file.txt; touch dir3/file.js # search for *.js, exclude dir1 find . -path './dir1' -prune -o -type f -iname '*.js' -print # search for *.js, exclude dir1 and dir2 find . \( -path './dir1' -o -path './dir2' \) -prune -o -type f -iname '*.js' -print

wisbucky

다음은 일부 경로를 제외하는 데 사용한 형식입니다.

 $ find ./ -type f -name "pattern" ! -path "excluded path" ! -path "excluded path"

이것을 사용하여 ".*" 경로에 없는 모든 파일을 찾았습니다.

 $ find ./ -type f -name "*" ! -path "./.*" ! -path "./*/.*"

user1882879

좋은 답변이 많이 있습니다. 명령의 각 요소가 무엇을 위한 것이고 그 뒤에 있는 논리를 이해하는 데 시간이 좀 걸렸습니다.

 find . -path ./misc -prune -o -name '*.txt' -print

find 는 현재 디렉토리에서 파일과 디렉토리를 찾기 시작하므로 find . .

-o 옵션은 논리적 OR을 나타내며 명령의 두 부분을 구분합니다.

 [ -path ./misc -prune ] OR [ -name '*.txt' -print ]

./misc 디렉토리가 아닌 모든 디렉토리 나 파일은 첫 번째 테스트를 통과하지 않습니다 -path ./misc . 그러나 그들은 두 번째 표현에 대해 테스트될 것입니다. *.txt 패턴과 일치 -print 옵션 때문에 인쇄됩니다.

find가 ./misc 디렉토리에 도달하면 이 디렉토리는 첫 번째 표현식만 만족합니다. 따라서 -prune 옵션이 적용됩니다. find 명령에 해당 디렉토리를 탐색 하지 않도록 지시합니다. 따라서 ./misc에 있는 파일이나 디렉토리는 find로 탐색되지 않으며 표현식의 두 번째 부분에 대해 테스트되지 않으며 인쇄되지 않습니다.


Istopopoki

-path -prune 접근 방식은 경로의 와일드카드에서도 작동합니다. 다음은 git 내부 디렉토리를 제외하고 여러 git 리포지토리를 제공하는 git 서버의 디렉토리를 찾는 find 문입니다.

 find . -type d \ -not \( -path */objects -prune \) \ -not \( -path */branches -prune \) \ -not \( -path */refs -prune \) \ -not \( -path */logs -prune \) \ -not \( -path */.git -prune \) \ -not \( -path */info -prune \) \ -not \( -path */hooks -prune \)

Wolfgang Fahl

여러 디렉토리를 제외하려면:

 find . -name '*.js' -not \( -path "./dir1" -o -path "./dir2/*" \)

디렉토리를 추가하려면 -o -path "./dirname/*" 추가하십시오.

 find . -name '*.js' -not \( -path "./dir1" -o -path "./dir2/*" -o -path "./dir3/*"\)

그러나 제외할 디렉토리가 많은 경우 정규식 을 사용해야 할 수도 있습니다.


JBENOIT

정리된 디렉토리 인쇄를 피하는 좋은 방법은 -prune -or -prune 뒤에 -print ( -exec 에서도 작동)를 사용하는 것입니다. 예를 들어, ...

 find . -path "*/.*" -prune -or -iname "*.j2"

모든 숨겨진 디렉토리를 건너뛰고 확장자가 `.j2"인 현재 디렉토리 아래의 모든 파일 경로를 인쇄합니다. 깔끔합니다. 그러나 위에서 언급한 대로 건너뛰는 각 디렉토리의 전체 경로도 인쇄합니다. 그러나 다음은하지 않습니다 ...

 find . -path "*/.*" -prune -or -iname "*.j2" -print

-iname 연산자 뒤와 -print 앞에 -and 가 있기 때문입니다. 이것은 연산 및 연관성의 부울 순서로 인해 -or 절의 오른쪽 부분에 바인딩합니다. 그러나 문서에는 숨겨진 -print (또는 그 사촌 중 하나 ... -print0 등)가 지정되지 않은 경우 숨겨진 -print가 있다고 말합니다. -or 인쇄의 왼쪽 부분이 아닌 이유는 무엇입니까? 분명히 (그리고 나는 맨 페이지를 처음 읽었을 때 이것을 이해하지 못했습니다) -print -or -exec ANYWHERE가 없으면 사실입니다. 이 경우 -print는 논리적으로 주변에 뿌려져 모든 것이 인쇄됩니다. 어떤 절에 하나의 print 스타일 연산이라도 표현되면 숨겨진 논리적 연산은 모두 사라지고 지정한 것만 얻습니다. 솔직히 말해서 나는 그 반대의 방법을 선호했을 수도 있지만 find 는 분명히 아무 일도 하지 않을 것이므로 있는 그대로의 의미가 있다고 생각합니다. 위에서 언급했듯이 이것은 모두 -exec 에서도 작동하므로 다음은 ls -la 목록을 제공하지만 각 숨겨진 디렉토리의 첫 번째 수준은 나열하지 않습니다.

 find . -path "*/.*" -prune -or -iname "*.j2" -exec ls -la -- {} +

나(및 이 스레드의 다른 사용자)의 경우 find 구문은 매우 바로크 양식이므로 항상 괄호를 사용하여 무엇이 무엇에 바인딩되는지 알 수 있도록 합니다. ...

 find . \( \( ... description of stuff to avoid ... \) -prune \) -or \ \( ... description of stuff I want to find ... [ -exec or -print] \)

이런 식으로 세계를 두 부분으로 설정하면 잘못되기가 어렵습니다. 누군가가 30개 이상의 답변을 읽고 투표할 가능성은 낮아 보이지만 희망할 수는 있지만 이것이 도움이 되기를 바랍니다. :-)


cycollins

작동 솔루션의 경우(Ubuntu 12.04(Precise Pangolin)에서 테스트됨)...

 find ! -path "dir1" -iname "*.mp3"

dir1 하위 폴더를 제외한 현재 폴더 및 하위 폴더에서 MP3 파일을 검색합니다.

사용하다:

 find ! -path "dir1" ! -path "dir2" -iname "*.mp3"

...dir1 및 dir2를 제외하려면


james dupin

find -name '*.js' -not -path './node_modules/*' -not -path './vendor/*'

와 동일하게 작동하는 것 같습니다

 find -name '*.js' -not \( -path './node_modules/*' -o -path './vendor/*' \)

IMO를 기억하기 쉽습니다.


Funkodebat

정규식을 사용하여 다음과 같이 검색한 일부 파일/디렉토리를 포함/제외할 수도 있습니다.

 find . -regextype posix-egrep -regex ".*\.(js|vue|s?css|php|html|json)$" -and -not -regex ".*/(node_modules|vendor)/.*"

이렇게 하면 모든 js, vue, css 등의 파일만 제공되지만 node_modulesvendor 폴더의 모든 파일은 제외됩니다.


supersan

한 번에 여러 경로를 무시하는 방법을 연구하는 사람이 있다면. bash 배열을 사용할 수 있습니다(GNU bash, 버전 4.4.20(1)-release에서 완벽하게 작동).

 #!/usr/bin/env bash # This script helps ignore unnecessary dir paths while using the find command EXCLUDE_DIRS=( "! -path /*.git/*" "! -path /*go/*" "! -path /*.bundle/*" "! -path /*.cache/*" "! -path /*.local/*" "! -path /*.themes/*" "! -path /*.config/*" "! -path /*.codeintel/*" "! -path /*python2.7/*" "! -path /*python3.6/*" "! -path /*__pycache__/*" ) find $HOME -type f ${EXCLUDE_DIRS[@]} # if you like fzf find $HOME -type f ${EXCLUDE_DIRS[@]} | fzf --height 40% --reverse

또한 어떤 이유로 인해 /bin/ 디렉토리 경로를 무시할 수 없습니다.


Bhupesh Varshney

이를 위해 정리 옵션을 사용할 수 있습니다. 예를 들어:

 find ./ -path ./beta/* -prune -o -iname example.com -print

또는 역 grep "grep -v" 옵션:

 find -iname example.com | grep -v beta

자세한 지침과 예제는 Linux find 명령 exclude 디렉토리에서 찾을 수 있습니다.


Siju V

TLDR: -path <excluded_path> -prune -o 옵션을 사용하여 루트 디렉토리를 이해하고 거기에서 검색을 조정하십시오. 제외된 경로의 끝에 / 를 포함하지 마십시오.

예시:

find / -path /mnt -prune -o -name "*libname-server-2.a*" -print


find 를 효과적으로 사용하려면 파일 시스템 디렉토리 구조를 잘 이해하는 것이 필수적이라고 생각합니다. rsnapshot (즉, rsync )을 사용하여 해당 콘텐츠의 약 절반이 백업된 멀티 TB 하드 드라이브가 있습니다. 물리적으로 독립적인(중복) 드라이브에 백업하지만 내 시스템 루트( / ) 디렉토리 /mnt/Backups/rsnapshot_backups/ :

 /mnt/Backups/ └── rsnapshot_backups/ ├── hourly.0/ ├── hourly.1/ ├── ... ├── daily.0/ ├── daily.1/ ├── ... ├── weekly.0/ ├── weekly.1/ ├── ... ├── monthly.0/ ├── monthly.1/ └── ...

/mnt/Backups/rsnapshot_backups/ 디렉토리는 현재 ~60M 파일 및 폴더와 함께 ~2.9TB를 차지합니다. 단순히 해당 콘텐츠를 탐색하는 데 시간이 걸립니다.

 ## As sudo (#), to avoid numerous "Permission denied" warnings: time find /mnt/Backups/rsnapshot_backups | wc -l 60314138 ## 60.3M files, folders 34:07.30 ## 34 min time du /mnt/Backups/rsnapshot_backups -d 0 3112240160 /mnt/Backups/rsnapshot_backups ## 3.1 TB 33:51.88 ## 34 min time rsnapshot du ## << more accurate re: rsnapshot footprint 2.9T /mnt/Backups/rsnapshot_backups/hourly.0/ 4.1G /mnt/Backups/rsnapshot_backups/hourly.1/ ... 4.7G /mnt/Backups/rsnapshot_backups/weekly.3/ 2.9T total ## 2.9 TB, per sudo rsnapshot du (more accurate) 2:34:54 ## 2 hr 35 min

/ (루트) 파티션에서 파일을 검색해야 할 때마다 백업 파티션을 통과하는 작업을 처리해야 합니다(가능하면 피해야 함).


이 스레드에서 다양하게 제안된 접근 방식( find . command 에서 디렉토리를 제외하는 방법 ) 중에서 허용된 답변을 사용하여 검색하는 것이 훨씬 더 빠르다 는 것을 알았습니다.

솔루션 1

libname-server-2.a rsnapshot 백업을 검색하고 싶지 않다고 가정해 보겠습니다. 신속하게 시스템 파일을 찾으려면, 경로 제외 사용 /mnt (즉, 사용 /mnt 하지 /mnt/ 또는 /mnt/Backups , 또는 ...)

 ## As sudo (#), to avoid numerous "Permission denied" warnings: time find / -path /mnt -prune -o -name "*libname-server-2.a*" -print /usr/lib/libname-server-2.a real 0m8.644s ## 8.6 sec <<< NOTE! user 0m1.669s sys 0m2.466s ## As regular user (victoria); I also use an alternate timing mechanism, as ## here I am using 2>/dev/null to suppress "Permission denied" warnings: $ START="$(date +"%s")" && find 2>/dev/null / -path /mnt -prune -o \ -name "*libname-server-2.a*" -print; END="$(date +"%s")"; \ TIME="$((END - START))"; printf 'find command took %s sec\n' "$TIME" /usr/lib/libname-server-2.a find command took 3 sec ## ~3 sec <<< NOTE!

... 단 몇 초 만에 해당 파일을 찾는 반면 훨씬 더 오래 걸립니다(모든 "제외된" 디렉토리를 통해 반복되는 것처럼 보임):

 ## As sudo (#), to avoid numerous "Permission denied" warnings: time find / -path /mnt/ -prune -o -name "*libname-server-2.a*" -print find: warning: -path /mnt/ will not match anything because it ends with /. /usr/lib/libname-server-2.a real 33m10.658s ## 33 min 11 sec (~231-663x slower!) user 1m43.142s sys 2m22.666s ## As regular user (victoria); I also use an alternate timing mechanism, as ## here I am using 2>/dev/null to suppress "Permission denied" warnings: $ START="$(date +"%s")" && find 2>/dev/null / -path /mnt/ -prune -o \ -name "*libname-server-2.a*" -print; END="$(date +"%s")"; \ TIME="$((END - START))"; printf 'find command took %s sec\n' "$TIME" /usr/lib/libname-server-2.a find command took 1775 sec ## 29.6 min

솔루션 2

이 스레드에서 제공되는 다른 솔루션( SO#4210042 )도 성능이 좋지 않습니다.

 ## As sudo (#), to avoid numerous "Permission denied" warnings: time find / -name "*libname-server-2.a*" -not -path "/mnt" /usr/lib/libname-server-2.a real 33m37.911s ## 33 min 38 sec (~235x slower) user 1m45.134s sys 2m31.846s time find / -name "*libname-server-2.a*" -not -path "/mnt/*" /usr/lib/libname-server-2.a real 33m11.208s ## 33 min 11 sec user 1m22.185s sys 2m29.962s

요약 | 결론

" 솔루션 1 "에 설명된 접근 방식 사용

 find / -path /mnt -prune -o -name "*libname-server-2.a*" -print

 ... -path <excluded_path> -prune -o ...

제외된 경로에 / 를 추가할 때마다 find 명령은 (모든 해당) /mnt/* 디렉토리에 재귀적으로 들어갑니다. 제 경우에는 /mnt/Backups/rsnapshot_backups/* 하위 디렉토리로 인해 다음이 추가로 포함됩니다. ~2.9TB의 파일 검색 가능! / 추가하지 않으면 검색이 거의 즉시(초 이내에) 완료됩니다.

"Solution 2"( ... -not -path <exclude path> ... ) 마찬가지로 제외된 디렉토리를 재귀적으로 검색하는 것처럼 보입니다. 제외된 일치 항목을 반환하지 않지만 해당 검색 시간을 불필요하게 소모합니다.


rsnapshot 백업 내에서 검색:

내 시간별/일별/주별/월별 rsnapshot 백업 중 하나에서 파일을 찾으려면:

 $ START="$(date +"%s")" && find 2>/dev/null /mnt/Backups/rsnapshot_backups/daily.0 -name '*04t8ugijrlkj.jpg'; END="$(date +"%s")"; TIME="$((END - START))"; printf 'find command took %s sec\n' "$TIME" /mnt/Backups/rsnapshot_backups/daily.0/snapshot_root/mnt/Vancouver/temp/04t8ugijrlkj.jpg find command took 312 sec ## 5.2 minutes: despite apparent rsnapshot size ## (~4 GB), it is in fact searching through ~2.9 TB)

중첩 디렉토리 제외:

여기, 내가 중첩 된 디렉토리를 제외 할, 예를 들어, /mnt/Vancouver/projects/ie/claws/data/* 때 검색에서 /mnt/Vancouver/projects/ :

 $ time find . -iname '*test_file*' ./ie/claws/data/test_file ./ie/claws/test_file 0:01.97 $ time find . -path '*/data' -prune -o -iname '*test_file*' -print ./ie/claws/test_file 0:00.07

제쳐두고: -print 를 추가하면 제외된 디렉토리의 출력이 억제됩니다.

 $ find / -path /mnt -prune -o -name "*libname-server-2.a*" /mnt /usr/lib/libname-server-2.a $ find / -path /mnt -prune -o -name "*libname-server-2.a*" -print /usr/lib/libname-server-2.a

Victoria Stuart

find . \( -path '.**/.git' -o -path '.**/.hg' \) -prune -o -name '*.js' -print

위의 예는 .git.hg 폴더를 제외한 현재 디렉토리 아래의 *.js .git.hg 폴더의 깊이는 중요하지 않습니다.

참고: 이것은 또한 작동합니다:

 find . \( -path '.*/.git' -o -path '.*/.hg' \) -prune -o -name '*.js' -print

하지만 여기서 주제를 벗어난 다른 도구와의 일관성을 위해 ** 표기법을 선호합니다.


Richard Gomes

이전 답변 중 어느 것도 Ubuntu에서 좋지 않습니다. 이 시도:

 find . ! -path "*/test/*" -type f -name "*.js" ! -name "*-min-*" ! -name "*console*"

나는 이것을 여기에서 발견했다


Sixro

이것은 Mac에서 나에게 적합합니다.

 find . -name *.php -or -path "./vendor" -prune -or -path "./app/cache" -prune

php 접미사가 붙은 검색 이름에 대해 vendorapp/cache 디렉토리를 제외합니다.


jiahut

find . -name '*.js' -\! -name 'glob-for-excluded-dir' -prune

The Archetypal Paul

다음 명령이 작동합니다.

 find . -path ./.git -prune -o -print

찾기에 문제가 있는 경우 -D tree 옵션을 사용하여 표현식 분석 정보를 봅니다.

 find -D tree . -path ./.git -prune -o -print

또는 -D all 을 사용하여 모든 실행 정보를 봅니다.

 find -D all . -path ./.git -prune -o -print

EIIPII

find 를 사용하여 xgettext 에 대한 파일 목록을 제공하고 특정 디렉토리와 그 내용을 생략하고 싶었습니다. -prune 과 결합된 -path 많은 순열을 시도했지만 내가 원하는 디렉토리를 완전히 제외할 수 없었습니다.

무시하고 싶었던 디렉토리 의 내용 을 무시할 수 있었지만 find 는 디렉토리 자체를 결과 중 하나로 반환하여 결과적으로 xgettext 가 충돌하게 되었습니다(디렉토리는 허용하지 않음, 파일만).

내 솔루션은 단순히 grep -v 를 사용하여 결과에서 원하지 않는 디렉토리를 건너뛰는 것이었습니다.

 find /project/directory -iname '*.php' -or -iname '*.phtml' | grep -iv '/some/directory' | xargs xgettext

find 대한 논쟁이 있는지 여부는 확실히 말할 수 없습니다. grep 을 사용하는 것은 약간의 두통 후에 빠르고 쉬운 해결책이었습니다.


Lemmings19

-path 또는 -not을 사용할 수 없는 이전 버전의 UNIX 사용자를 위해

SunOS 5.10 bash 3.2 및 SunOS 5.11 bash 4.4에서 테스트됨

 find . -type f -name "*" -o -type d -name "*excluded_directory*" -prune -type f

JaredTS486

how-to-use-prune-option-of-find-in-sh -prune 작동 방식에 대한 Laurence Gonsalves 의 훌륭한 답변입니다.

다음은 일반적인 솔루션입니다.

 find /path/to/search \ -type d \ \( -path /path/to/search/exclude_me \ -o \ -name exclude_me_too_anywhere \ \) \ -prune \ -o \ -type f -name '*\.js' -print

/path/to/seach/ 여러 번 입력하지 않으려면 findpushd .. popd 쌍으로 래핑하십시오.

 pushd /path/to/search; \ find . \ -type d \ \( -path ./exclude_me \ -o \ -name exclude_me_too_anywhere \ \) \ -prune \ -o \ -type f -name '*\.js' -print; \ popd

go2null

위의 명령을 시도했지만 "-prune"을 사용하는 사람 중 누구도 저에게 적합하지 않습니다. 결국 아래 명령으로 이것을 시도했습니다.

 find . \( -name "*" \) -prune -a ! -name "directory"

Jolly Liu

/var 디렉토리에서 검색을 제외하고 모든 서버에서 landscape.jpg 를 찾고 다음과 같이 작동했습니다.

find / -maxdepth 1 -type d | grep -v /var | xargs -I '{}' find '{}' -name landscape.jpg

find / -maxdepth 1 -type d / 모든 d 디렉토리를 나열합니다.

grep -v /var 는 목록에서 `/var'를 제외합니다.

xargs -I '{}' find '{}' -name landscape.jpg 목록에서 각 디렉토리/결과로 find 와 같은 모든 명령 실행


adrianTNT

출처 : http:www.stackoverflow.com/questions/4210042/how-to-exclude-a-directory-in-find-command

반응형