backend

리눅스 파일 검색: locate, find 기본 사용법, 이것만 알면 쉽다

seul chan 2020. 12. 20. 22:33

17. Searching for files

locate

database를 바탕으로 주어진 substring과 맞는 파일을 탐색.

updatedb라는 프로그램이 정기적으로 cron job으로 파일 데이터베이스를 업데이트한다.

find

locate가 파일을 이름으로만 찾았다면 find 프로그램은 특정 디렉토리에서 다양한 옵션과 특성으로 파일을 찾을 수 있다.

find ~

# wordcount
find ~ | wc -l  

Options (Test)

find에는 다양한 옵션 (test라고 부름)이 존재한다.

대표적인 옵션은 -type.

# directory만 찾기
find ~ -type d | wc -l

# file 찾기
find ~ -type f | wc -l

# size option
find ~ -type f -name "*.JPG" -size +1M | wc -l

그 외 옵션들은 man page에서 확인 가능하다.

Operators

-or and, not, () (그룹)과 같은 operator도 사용 가능하다.

operator를 사용하지 않고 옵션을 연달아서 쓰면 -and가 생략된것

actions

-delete, -ls, -print와 같은 미리 정의된 액션이 있음.

find ~ -type f -name '*.bak' -delete

-delete 옵션을 쓰기 전에는 -print로 확인하는 것이 좋음

User-defined action

위에서 미리 정의된 액션 이외에도 -exec 를 사용하여 원하는 액션을 수행시킬 수 있다

-exec command '{}' ';'

-delete와 같은 액션은 다음과 같다.

-exec rm '{}' ';'

중괄호와 세미콜론은 쉘에서 특수하게 처리됨으로 quoted나 escaped 되어야한다.

exec 대신 -ok를 사용하면 interactive하게 사용 (명령어 실행 전에 prompt로 띄워줌)

find ~ -type f -name 'foo*' -ok ls -l '{}' ';'
< ls ... /home/me/bin/foo > ? y
-rwxr-xr-x 1 me   me 224 2007-10-29 18:44 /home/me/bin/foo
< ls ... /home/me/foo.txt > ? y
-rw-r--r-- 1 me   me   0 2016-09-19 12:53 /home/me/foo.txt

Improving efficiency

위에서는 파일 두개가 찾아졌기 때문에 ls -l 명령어가 두 번 실행된다.

하지만 ls -l file1 file2 처럼 파일 두 개를 한 번의 명령어에서 사용할 수 있는데, 이런 경우 다음과 같이 사용 가능.

find ~ -type f -name 'foo*' -exec ls -l '{}' +

xargs

xargs는 standard input으로 intput을 받고, 이를 특정 커맨드의 argument로 넘겨준다.

이를 find와 사용하면 아주 좋음

find ~ -type f -name 'foo*' -print | xargs ls -l

실제 사용 예시

# 테스트용 파일 생성
root@3c28bc830cb6:~# mkdir -p playground/dir-{001..100}
root@3c28bc830cb6:~# touch playground/dir-{001..100}/file-{A..Z}

# file-A 파일 개수 확인
root@3c28bc830cb6:~# find playground -type f -name 'file-A' | wc -l
100

권한을 일괄 확인 후 수정해보자. 파일인 경우 600, 디렉토리인 경우 700이 아니면 수정하는 명령어.

# permission이 600, 700이 아닌 개수 확인
root@3c28bc830cb6:~# find playground \( -type f -not -perm 600 \) -or \( -type d -not -perm 700 \) | wc -l
2701

# 해당 파일을 600, 700으로 수정
root@3c28bc830cb6:~# find playground \( -type f -not -perm 600 -exec chmod 600 '{}' ';' \) -or \( -type d -not
-perm 700 -exec chmod 700 '{}' ';' \)

# 다시 개수 확인
root@3c28bc830cb6:~# find playground \( -type f -not -perm 600 \) -or \( -type d -not -perm 700 \) | wc -l
0

괄호 사이에는 띄어쓰기가 필수