TECH / / 2023. 1. 31. 12:59

Linux find 명령어 옵션 및 예제

반응형

IT 실무에서 많이 사용하는 Linux find 명령어에 대해서 자세하게 알아보겠습니다. find 명령어는 매우 강력하여 매우 광범위하게 사용되는 리눅스 명령어입니다. 

 

find 명령어는 이름, 크기, 유형 및 수정 시간과 같은 기준을 사용할 수 있습니다. 다음은 몇 가지 일반적인 사용 예입니다:

 

 

find 명령 사용 예제

 

  • 이름으로 파일 찾기 방법:  find /path/to/search -name "file-name"
  • 지정된 크기보다 큰 파일 찾기:  find /path/to/search -size +100M
  • 지정된 시간 범위 내에서 수정된 파일 찾기: find /path/to/search -mtime -30
  • 유형에 따라 파일 찾기: find /path/to/search -type f (파일의 경우) or  find /path/to/search -type d (디렉토리의 경우) 
  • 일치하는 파일에 대한 명령 찾기: find /path/to/search -name "*.txt" -exec cat {} \;
  • 확장자가 .txt인 현재 디렉터리의 모든 파일 찾기 : find . -name "*.txt"
  • 지난 30일 동안 수정된 "/dir002" 디렉터리 내에 모든 파일 찾기 : find /dir002 -mtime -30
  • /var/log 디렉토리 내에 사이트가 100MB 이상인 파일 모두 찾기 : find /var/log -size +100M
  • 현재 디렉토리에서 확장자가 tmp인 모든 파일 찾아서 지우기 : find . -name "*.tmp" -delete
  • 현재 디렉토리 안에서 문자열이 example 포함된 파일을 모두 찾고 파일 이름과 줄번호를 출력 : find . -name "*" -exec grep -Hn "example" {} \;

 

find bash script example

 

linux find 명령어를 이용한 bash script 예제를 살펴보겠습니다.

 

#!/bin/bash

# Define the directory to search in
search_dir="/var/log"

# Define the file extension to search for
file_extension=".log"

# Define the number of days to search back
days_back=30

# Search for files in the search_dir with the specified file_extension and modified in the last days_back days
files=$(find $search_dir -name "*$file_extension" -mtime -$days_back)

# Check if any files were found
if [ -z "$files" ]; then
  echo "No files found."
else
  # Loop through each file found
  for file in $files
  do
    # Print the name of the file
    echo $file
  done
fi

 

이 bash script는 "/var/log" 디렉토리에서 지난 30일 동안 수정된 확장자가 ".log"인 파일을 모두 검색하여 찾아줍니다. 발견된 파일 이름은 터미널에 인쇄됩니다. 스크립트를 수정하여 사용해도 됩니다. 예를 들어 검색 디렉토리, 파일 확장명 또는 검색 기간(일자)을 변경하여 사용해도됩니다.

 

위 내용은 "find" 명령에서 사용할 수 있는 옵션별 몇 가지 예시입니다. 보다 상세한 정보나 사용 예제를 보려면 터미널 창에서 man find를 실행하여 man 페이지를 참조하시면 더욱 많은 정보를 확인할수있습니다.

 

 

반응형
  • 네이버 블로그 공유
  • 네이버 밴드 공유
  • 페이스북 공유
  • 카카오스토리 공유