![현재 작업 디렉터리의 가장 가까운 조상에서 특정 파일을 찾습니다.](https://linux55.com/image/89721/%ED%98%84%EC%9E%AC%20%EC%9E%91%EC%97%85%20%EB%94%94%EB%A0%89%ED%84%B0%EB%A6%AC%EC%9D%98%20%EA%B0%80%EC%9E%A5%20%EA%B0%80%EA%B9%8C%EC%9A%B4%20%EC%A1%B0%EC%83%81%EC%97%90%EC%84%9C%20%ED%8A%B9%EC%A0%95%20%ED%8C%8C%EC%9D%BC%EC%9D%84%20%EC%B0%BE%EC%8A%B5%EB%8B%88%EB%8B%A4..png)
find를 통해 특정 파일을 찾는 방법을 찾고 싶습니다.위로하위 디렉터리를 재귀적으로 검색하는 대신 디렉터리 구조에서 검색합니다.
하나 있다노드 모듈이 내가 원하는 것을 정확히 수행하는 것 같습니다., 하지만 JavaScript나 유사한 패키지 설치에 의존하고 싶지 않습니다. 이를 수행할 수 있는 쉘 명령이 있습니까? 이를 수행할 수 있는 방법이 있습니까 find
? 아니면 구글링으로 찾을 수 없는 표준적인 방법인가요?
답변1
직역한 내용입니다구성 알고리즘 찾기일반 쉘 명령(bash, ksh 및 zsh에서 테스트됨)에서 성공에는 반환 코드 0을 사용하고 NULL/실패에는 1을 사용합니다.
findconfig() {
# from: https://www.npmjs.com/package/find-config#algorithm
# 1. If X/file.ext exists and is a regular file, return it. STOP
# 2. If X has a parent directory, change X to parent. GO TO 1
# 3. Return NULL.
if [ -f "$1" ]; then
printf '%s\n' "${PWD%/}/$1"
elif [ "$PWD" = / ]; then
false
else
# a subshell so that we don't affect the caller's $PWD
(cd .. && findconfig "$1")
fi
}
예제 실행, 도난당한 설정 복사 및 확장스티븐 해리스답변:
$ mkdir -p ~/tmp/iconoclast
$ cd ~/tmp/iconoclast
$ mkdir -p A/B/C/D/E/F A/good/show
$ touch A/good/show/this A/B/C/D/E/F/srchup A/B/C/thefile
$ cd A/B/C/D/E/F
$ findconfig thefile
/home/jeff/tmp/iconoclast/A/B/C/thefile
$ echo "$?"
0
$ findconfig foobar
$ echo "$?"
1
답변2
현재 디렉토리를 확인하고 찾을 수 없는 경우 마지막 구성 요소를 제거하는 간단한 루프가 작동합니다.
#!/bin/bash
wantfile="$1"
dir=$(realpath .)
found=""
while [ -z "$found" -a -n "$dir" ]
do
if [ -e "$dir/$wantfile" ]
then
found="$dir/$wantfile"
fi
dir=${dir%/*}
done
if [ -z "$found" ]
then
echo Can not find: $wantfile
else
echo Found: $found
fi
예를 들어, 이것이 디렉토리 트리인 경우:
$ find /tmp/A
/tmp/A
/tmp/A/good
/tmp/A/good/show
/tmp/A/good/show/this
/tmp/A/B
/tmp/A/B/C
/tmp/A/B/C/thefile
/tmp/A/B/C/D
/tmp/A/B/C/D/E
/tmp/A/B/C/D/E/F
/tmp/A/B/C/D/E/F/srchup
$ pwd
/tmp/A/B/C/D/E/F
$ ./srchup thefile
Found: /tmp/A/B/C/thefile
우리가 찾고 있는 것을 찾을 때까지 트리 위로 검색이 진행되는 것을 볼 수 있습니다.
답변3
한 가지 방법은 다음과 같습니다.
#! /bin/sh
dir=$(pwd -P)
while [ -n "$dir" -a ! -f "$dir/$1" ]; do
dir=${dir%/*}
done
if [ -f "$dir/$1" ]; then printf '%s\n' "$dir/$1"; fi
물리적 디렉토리를 확인하는 대신 기호 링크를 따르려면 pwd -P
로 바꾸십시오.pwd -L