Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux基礎 >> Linux技術

Linux find 命令的常用用法整理

man 文檔中 find 的一般形式為 find [-H] [-L] [-P] [-D debugopts] [-Olevel] [path...] [expression],其中前幾個選項並不常用,日常可簡化為:

find [path...] [expression],即 find 【路徑名】【選項】【查找的檔名或目錄名】

- path:查找的目錄路徑,. 表示當前目錄,/ 表示根目錄。
- expression:分為 -options [-print -exec -ok ...]。

- -options:指定常用選項。
- -print:把匹配的檔案輸出到標準輸出。
- -exec:對匹配的檔案執行指定 shell 命令,形式為 'command' {} \;(注意 {} 與 \; 之間的空格)。例如刪除大小為零的檔案:find ./ -size 0 -exec rm {} \;;用 ls -l 列出匹配檔案:find . -type f -exec ls -l {} \;;刪除 /logs 中 5 日前的檔案:find /logs -type f -mtime +5 -exec rm {} \;。
- -ok:同 -exec,但每執行一條命令前都會提示確認,如 find . -name "*.conf" -mtime +5 -ok rm {} \;。

也有人把 find 結構總結為:find start_directory test options criteria_to_match action_to_perform_on_results。

記住:若從某目錄開始查找需寫絕對路徑,若從當前目錄開始可直接用「.」。

find .:列出當前目錄下所有檔案與目錄。Linux find 命令的常用用法整理Linux find 命令的常用用法整理Linux find 命令的常用用法整理Linux find 命令的常用用法整理

find /home/admin/text -name kuo:顯示 text 目錄下所有同名檔案。Linux find 命令的常用用法整理Linux find 命令的常用用法整理find /home/admin/text -iname kuo:不區分大小寫。Linux find 命令的常用用法整理

find . -name "*.txt" -o -name "*.pdf":查找 .txt 與 .pdf 結尾的檔案。Linux find 命令的常用用法整理Linux find 命令的常用用法整理

匹配檔案路徑:find /usr/ -path "*local*";基於正則表達式匹配:find . -regex ".*\(\.txt\|\.pdf\)$",忽略大小寫用 -iregex。

否定參數:找出 /home 下不是 .txt 結尾的檔案 find /home ! -name "*.txt"。Linux find 命令的常用用法整理Linux find 命令的常用用法整理

按檔案類型搜索:類型參數 f 普通檔、l 符號連接、d 目錄、c 字符設備、b 塊設備、s 套接字、p Fifo,如 find . -type【類型參數】。Linux find 命令的常用用法整理Linux find 命令的常用用法整理

按目錄深度:向下最大深度 3 用 find . -maxdepth 3 -type f;至少 2 個子目錄用 find . -mindepth 2 -type f。

按時間戳:Linux 檔案有三種時間戳——訪問時間(-atime/天、-amin/分)、修改時間(-mtime、-mmin)、變化時間(-ctime、-cmin)。如 find . -type f -atime -2(2 天內訪問)、-atime 7(恰好 7 天前)、-atime +7(超過 7 天)、-amin +10(超過 10 分鐘)、-newer file.log(比 file.log 修改時間更長)。Linux find 命令的常用用法整理Linux find 命令的常用用法整理

按檔案大小:單位 b(512 位元組)、c(位元組)、w(字)、k、M、G。如 find . -type f -size +10k(大於 10KB)、-size -10k(小於 10KB)、-size 10k(等於 10KB)。Linux find 命令的常用用法整理Linux find 命令的常用用法整理

刪除匹配檔案:find . -type f -name "*.txt" -delete。

按權限/所有權:find . -type f -perm 777(權限 777)、! -perm 644(權限非 644 的 php)、-user tom、-group sunk。Linux find 命令的常用用法整理Linux find 命令的常用用法整理

借助 -exec 與其他命令結合:把 root 的檔案改為 tom 擁有 find . -type f -user root -exec chown tom {} \;;{} 會被相應檔名替換。刪除家目錄 .txt 用 -ok rm {} \;(會提示確認);拼接所有 .txt 到 all.txt 用 -exec cat {} \; > all.txt;移動 30 天前 .log 用 -mtime +30 -name "*.log" -exec cp {} old \;;以「File:檔名」形式打印用 -exec printf "File: %s\n" {} \;;要在 -exec 中執行多條命令可寫成 -exec ./text.sh {} \;。

搜索但跳出指定目錄:跳過子目錄 sk 用 find . -path "./sk" -prune -o -name "*.txt" -print。

其他技巧:列出所有長度為零的檔案 find . -empty。Linux find 命令的常用用法整理Linux find 命令的常用用法整理

Copyright © Linux教程網 All Rights Reserved