2011年11月16日 星期三

[Linux 命令] Linux find 命令使用詳解


轉載自 這裡
前言 :
Linux下find命令在目錄結構中搜索文件,並執行指定的操作。Linux下find命令提供了相當多的查找條件,功能很強大. Linux中find常見用法示例 如下 :
find path -option [ -print ] [ -exec -ok command ] {} \;

其中 :
-print 將查找到的文件輸出到標准輸出
-exec command {} \; 將查到的文件執行command操作,{} 和 \;之間有空格
-ok 和-exec相同,只不過在操作前要詢用戶

參數說明 :
-name filename #查找名為filename的文件
-perm #按執行權限來查找
-user username #按文件屬主來查找
-group groupname #按組來查找
-mtime -n/+n #按文件更改時間來查找文件,-n指n天以內,+n指n天以前
-atime -n/+n #按文件訪問時間來查
-ctime -n/+n #按文件創建時間來查找文件,-n指n天以內,+n指n天以前
-nogroup #查無有效屬組的文件,即文件的屬組在/etc/groups中不存在
-nouser #查無有效屬主的文件,即文件的屬主在/etc/passwd中不存
-newer f1 !f2 #查更改時間比f1新但比f2舊的文件
-type b/d/c/p/l/f #查是塊設備、目錄、字符設備、管道、符號鏈接、普通文件
-size n[c] #查長度為n塊[或c字節]的文件
-depth #使查找在進入子目錄前先行查找完本目錄
-mount #查文件時不跨越文件系統mount點
-follow #如果遇到符號鏈接文件,就跟蹤鏈接所指的文件
-cpio #對匹配的文件使用cpio命令,將他們備份到磁帶設備中
-prune #忽略某個目錄

更多信息可以查看:《Linux下find命令詳解》、《Linux下find命令實例》.

範例說明 :
1. 在/tmp中查找所有的*.h,並在這些文件中查找“test",最後打印出所有包含"SYSCALL_VECTOR"的文件名
#find /tmp -name "*.h" | xargs -n50 grep test
/tmp/test1.h:This is for test2
/tmp/test.h:This is for test1
#find /tmp -name "*.h" -exec grep "test" {} \; -print
This is for test2
/tmp/test1.h
This is for test1
/tmp/test.h

2. 查找當前目錄下大於3M的文件
#find . -size +3000k -exec ls -ld {} \;
-rw-r--r-- 1 root root 6671029 Nov 10 16:40 ./NCITTools_ATF.jar

3. 將find出來的東西拷到另一個地方
#find *.c -exec cp {} /tmp \; -print
test.c <將 test.c 複製到 /tmp 下>
如果有特殊文件,可以用cpio,也可以用這樣的語法:
find dir -name filename -print | cpio -pdv newdir

4. 查找 2011-11-16 時更改過的文件
#A=`find . -name "*.sh"` | ls -l --full-time $A 2>/dev/null | grep "2011-11-16"
-rw-r--r-- 1 root root 1538 2011-11-16 16:12:32.000000000 +0800 1kfn.pcap
-rw-r--r-- 1 root root 489 2011-11-16 16:12:47.000000000 +0800 45fn.pcap
-rw-r--r-- 1 root root 3569 2011-11-16 09:34:29.000000000 +0800 45f.pcap

其它常用語法 :
1. 基本用法
find / -name 文件名
find ver1.d ver2.d -name '*.c' -print #查找ver1.d,ver2.d *.c文件並打印
find . -type d -print #從當前目錄查找,僅查找目錄,找到後,打印路徑名。可用於打印目錄結構

2. 無錯誤查找
find / -name access_log 2 >/dev/null

3. 按尺寸查找
find / -size 1500c #查找1,500字節大小的文件,c表示字節
find / -size +1500c #查找大於1,500字節大小的文件,+表示大於
find / -size -1500c #查找小於1,500字節大小的文件,-表示小於

4. 按時間
find / -amin n #最後n分鍾
find / -atime n #最後n天
find / -cmin n #最後n分鍾改變狀態
find / -ctime n #最後n天改變狀態

5. 其它
find / -empty #空白文件、空白文件夾、沒有子目錄的文件夾
find / -false #查找系統中總是錯誤的文件
find / -fstype type #找存在於指定文件系統的文件,如type為ext2
find / -gid n #group id為n的文件
find / -group gname #group 名為gname的文件
find / -depth n #在某層指定目錄中優先查找文件內容
find / -maxdepth levels #在某個層次目錄中按遞減方式查找

6. 邏輯
-and 條件與 -or 條件或

7. 查找字符串
find . -name '*.html' -exec grep 'mailto:'{}
This message was edited 14 times. Last update was at 17/11/2011 15:55:01

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...