2015/05/17

find 사용법 (Update:20150910)

http://kiros33.blog.me/130136273131

  
Rivision History
2015/05/18 00:19:31 - [펌] find 명령의 25개 간단한 예제 링크 추가
2015/05/18 00:32:47 - while 을 사용해서 변수 처리하는 방법, 파일명(filename), 확장자(extention) 분리하는 방법
2015/09/10 11:31:27 - 디렉토리 구조를 포함해서 파일 복사하기 항목 추가

Reference Page

>>>>> 파일 크기, 기본은 Byte이고 kMGTP를 지정해서 단위를 선택 (Update:20131231)

-size n[ckMGTP]
True if the file's size, rounded up, in 512-byte blocks is n.  If n is followed by a c, then the primary is true if the file's size is n bytes (characters).  Similarly if n is followed by a scale indicator then the file's size is compared to n scaled as:

k       kilobytes (1024 bytes)
M       megabytes (1024 kilobytes)
G       gigabytes (1024 megabytes)
T       terabytes (1024 gigabytes)
P       petabytes (1024 terabytes)

# 10M 보다 큰 파일
find . -type f -size +10M
# 100k 보다 작은 파일
find . -type f -size -100k
  

>>>>> 파일의 유형(type) (Update:20131231)
  
-type t
True if the file is of the specified type.  Possible file types are as follows:

b       block special
c       character special
d       directory
f       regular file
l       symbolic link
p       FIFO
s       socket
  
# 타입이 심볼릭 링크인 모든 목록을 ls 명령으로 보기
find . -type l -ls
# 타입이 디렉토리인 모든 목록 보기
find . -type d
# 타입이 파일이고 이름이 a로 시작하는 목록 보기
find . -type f -name 'a*'
  

>>>>> 파일의 시간 정보 (Update:20131231)
   
-mmin n
True if the difference between the file last modification time and the time find was started, rounded up to the next full minute, is n minutes.

-mtime n[smhdw]
If no units are specified, this primary evaluates to true if the difference between the file last modification time and the time find was started, rounded up to the next full 24-hour period, is n 24-hour periods.

If units are specified, this primary evaluates to true if the difference between the file last modification time and the time find was started is exactly n units.  Please refer to the -atime primary description for information on supported time units.

-cmin n
True if the difference between the time of last change of file status information and the time find was started, rounded up to the next full minute, is n minutes.

-ctime n[smhdw]
If no units are specified, this primary evaluates to true if the difference between the time of last change of file status information and the time find was started, rounded up to the next full 24-hour period, is n 24-hour periods.

If units are specified, this primary evaluates to true if the difference between the time of last change of file status information and the time find was started is exactly n units. Please refer to the -atime primary description for information on supported time units.

-amin n
True if the difference between the file last access time and the time find was started, rounded up to the next full minute, is n minutes.

-atime n[smhdw]
If no units are specified, this primary evaluates to true if the difference between the file last access time and the time find was started, rounded up to the next full 24-hour period, is n 24-hour periods.

If units are specified, this primary evaluates to true if the difference between the file last access time and the time find was started is exactly n units.  Possible time units are as follows:

s       second
m       minute (60 seconds)
h       hour (60 minutes)
d       day (24 hours)
w       week (7 days)

Any number of units may be combined in one -atime argument, for example, ``-atime -1h30m''. Units are probably only useful when used in conjunction with the + or - modifier.
  
# 수정된지 100일이 지난 파일 목록록
find . -type f -mtime +100 -ls
# 오늘 수정된 파일 목록
find . -type f -mtime -1 -ls
# 1분안에 수정된 파일 목록
find . -type f -mmin -1 -ls
# 3분안에 액세스된 파일 목록
find . -type f -amin -3 -ls
# 2분 50초안에 수정된 파일 목록
find . -type f -atime -2m50s
  

>>>>> 권한 및 소유자 (Update:20131231)

# 파일시스템 전체( / )에서 SUID/SGID가 설정된 모든 파일 목록을 얻음
find / -type f \( -perm -04000 -o -perm -02000 \) -ls
# 소유자가 없는 파일 목록을 얻음 (사용자는 이미 삭제했는데, 파일이 남은 경우)
find / -nouser -o -nogroup
   
  
>>>>> 에러 메시지 제외하기

find / -name search 2> /dev/null
some_command >/dev/null 2>&1 # ">/dev/null" assumes stdout, "2>&1" redirects stderr to stdout (and hence, to /dev/null in this example)

0:stdin
1:stdout
2:stderr


>>>>> 특정 경우 제외하기 (여러 조건 동시 사용 가능)

find . -type d ! -regex ".*\/.svn.*" -exec mkdir -p ${DST_BASE}/{} \;
find . -type d -regex ".*\/oam.*" ! -regex ".*\/.svn.*" -exec mkdir -p ${DST_BASE}/{} \;


>>>>> -or 나 -and 

find ../../ -name "ar*.h" -or -name "ar*.c"


>>>>> 특정 목록만 추출해서 파일명과 파일 크기 보기

ls -al `find . -name "tc-*" ! -name "*md5"` | awk '{print $8,"\t"$5}' | sort


>>>>> find 사용시 정규식 종류 선택

find 에서 -regex 옵션을 사용할 때 정규식 종류는 emacs 가 기본값 입니다. (정규식 특수기호를 다 \ 처리해야 되서 번거로움) 
따라서 정규식 종류를 바꿀 때는 -regextype 옵션을 통해 posix-awk, posix-basic, posix-egrep, posix-extended 등의 종류를 직접 지정해줘야 합니다. 
find . -regextype posix-egrep -regex ".*\.(:?c|h)"


>>>>> 맥에서 정규식 사용
  
find -E . -type f -regex '.* - 2012[0-9]{4}.*'


>>>>> 맥에서 파일을 찾고 특정 위치에 폴더 구조를 유지한채 파일 복사
  
find -E . -type f -regex '.* - 2012[0-9]{4}.*' -exec bash -c 'mkdir -p "${HOME}/Downloads/2012/$(dirname "{}")";cp "{}" "${HOME}/Downloads/2012/$(dirname "{}")"' \;
  
#대상을 찾아서 동일한 디렉토리 구조로 복사 find -E . -type f -regex '.* - 2012[0-9]{4}.*\.(zip|rar|7z)' -exec bash -c 'mkdir -p "${HOME}/Downloads/backup/$(dirname "{}")";cp "{}" "${HOME}/Downloads/backup/$(dirname "{}")"' \; #대상을 찾아서 .store 확장자를 추가 find -E . -type f -regex '.* - 2012[0-9]{4}.*\.(zip|rar|7z)' -exec touch {}.store \; #대상을 찾아서 삭제 find -E . -type f -regex '.* - 2012[0-9]{4}.*\.(zip|rar|7z)' -exec rm -v {} \;
  
  
>>>>> 디렉토리 구조만 복사하기

find . -type d -exec mkdir target_directory/{} \;


>>>>> 디렉토리 구조를 포함해서 파일 복사하기

리눅스에서는 --parents 옵션을 통해 소스 파일의 부모 폴더 구조까지 복사해주는 기능이 있습니다.

하지만 맥에서는 해당 옵션을 사용할 수 없습니다. 결국 디렉토리 구조를 만들어 줄 필요가 있습니다.
find 등을 통해서 파일목록을 확보하고 다음 명령어를 적절하게 배치해서 부모 폴더를 만들어 줄 수 있습니다.

명령 구조
mkdir -p "/targetdir/`dirname '/sourcedir/full/path/filename.ext'`/"

실행해보면 다음과 같이 보여집니다.
echo mkdir -p "/targetdir/`dirname '/sourcedir/a/b/c/d/1.zip'`/"
mkdir -p /targetdir//sourcedir/a/b/c/d/
  
위 명령에서 echo를 제외하면 실제로 디렉토리가 생성됩니다.
  

>>>>> multiple commands 

find . -name find-pattern  -exec echo command1 {} \; -exec echo command2 {} \;


>>>>> multiple commands with xargs 

find . -name find-pattern | find . -name find-pattern | xargs -I{} sh -c '{ echo command1 {} ; echo command2 {} ; }'


>>>>> 파일 확장자를 검색해서 변경하는 방법 (JPG를 jpg로) (Update:2014/10/06 17:55:47)
  
while read file
do
  name="${file/.JPG/}"
  echo mv "$name.JPG" "$name.jpg"
done < <(find . -type f -name '*.JPG') >> list.txt


>>>>> bash 로 인수를 넘겨서 처리 하는 방법

# 변수 치환 방법을 사용해서 "ORIGINAL_TEXT"를 "REPLACE_TEXT"로 바꾸기
find . -type d -exec bash -c 'mv $0 ${0/ORIGINAL_TEXT/REPLACE_TEXT}' {} \;
# 모든 "ORIGINAL_TEXT" 문자열을 "REPLACE_TEXT" 로 바꾸기
find . -type d -exec bash -c 'echo mv \"$0\" "$(echo "$0" | sed s/ORIGINAL_TEXT/REPLACE_TEXT/g)"' {} \;

# 모든 "ORIGINAL_TEXT" 로 끝나는 문자열을 "REPLACE_TEXT" 로 바꾸기
find . -type d -exec bash -c 'echo mv \"$0\" "$(echo "$0" | sed s/ORIGINAL_TEXT\$/REPLACE_TEXT/g)"' {} \;

# . (Any Char) 에 개행 문자 (\n or \r)를 포함하고 여러 줄에 적용되도록 옵션을 적용, 모든 "ORIGINAL_TEXT" 문자열을 "REPLACE_TEXT" 로 바꾸기
find . -type d -exec bash -c 'echo mv ${0} $(echo ${0} | perl -p -e "s/ORIGINAL_TEXT/REPLACE_TEXT/gms")' {} \;


>>>>> 특정 경로를 동작에서 제외시키는 방법 (Update:20150210)

 find / -type d \( -path '/media/*' -prune \) -o -name 'security' -print
/lib/x86_64-linux-gnu/security
/lib/security
/usr/lib/jvm/java-7-openjdk-amd64/jre/lib/security
/usr/src/linux-headers-3.13.0-24-generic/security
/usr/src/linux-headers-3.13.0-24-generic/include/config/nfsd/v4/security
/usr/src/linux-headers-3.13.0-24-generic/include/config/default/security
/usr/src/linux-headers-3.13.0-24-generic/include/config/security
/usr/src/linux-headers-3.13.0-24-generic/include/config/nfs/v4/security
/usr/src/linux-headers-3.13.0-24/security
/etc/security
/etc/java-7-openjdk/security
/sys/kernel/security
  

>>>>> 2015/05/18 00:32:47 - while 을 사용해서 변수 처리하는 방법, 파일명(filename), 확장자(extention) 분리하는 방법
  
 find . -type f -name '*.pdf' -print0 | while IFS= read -r -d '' filename; do exiftool -overwrite_original -Title="$(basename ${filename%.*})" -Author="글쓴이" -Subject="주제" "${filename}"; done
    1 image files updated
    1 image files updated
    1 image files updated
    1 image files updated
    1 image files updated
    1 image files updated
    1 image files updated
    1 image files updated
  
   
검색 : Linux, 리눅스, find, Command, 명령, Example, 예 예제, Sample, 샘플, Usage, 용법, 사용법,

댓글 없음:

댓글 쓰기