1、linux中包含大量的文件,對于文件查找,linux提供了find命令。
find是一個非常有效的工具,它可以遍歷目標目錄甚至整個文件系統來查找某些文件或目錄:
find [path...] [expression]
其中expression包括三種:options、tests和actions。多個表達式之間被操作符分隔,當操作符被省略時,表示使用了默認操作符-and。
當表達式中不包含任何actions時,默認使用-print,也就是打印出搜索到的所有文件,用換行分隔。
其實可以將三種表達式均視為選項,表示對搜索的某種限制(如-maxdepth表示搜索路徑的最大深度)、或對找到的目標文件的某種測試(如-readable判斷是否可讀)、或對結果采取的某種動作(如-print)。
選項-name pattern搜索文件名:
[root@centos7 temp]# find /root/* -name "file?" /root/file1/root/temp/file1/root/temp/file2/root/temp/file3/root/temp/file4/root/temp/file5/root/temp/file6/root/temp/file7/root/temp/file8/root/temp/file9[root@centos7 temp]#
此例中搜索目錄/root下所有文件,找出匹配file?的文件名,同時由于沒有指定action,所以使用默認的-print將結果打印出來。find命令中,搜索路徑和某些文件名的表示可以使用shell通配符(見上一篇),但為了避免混淆,處于選項后的通配符需要被引號引起來。
選項-maxdepth n指定搜索路徑的最大深度:
[root@centos7 ~]# find /root -maxdepth 1 -name "file?" #注意表達式之間的隱含操作符 -and/root/file1[root@centos7 ~]#
本例中指定最大深度為1,表示只搜索/root目錄,而不進入任何它的子目錄去搜索。
和此選項相對應,-mindepth表示指定搜索路徑的最小深度。
選項-user name按照文件屬主來查找文件:
[root@centos7 ~]# find /root/temp -name "file?" -user learner/root/temp/file1/root/temp/file2[root@centos7 ~]#
或者類似選項-uid n表示按文件屬主的uid,-gid n表示按文件所屬組的gid,-group name表示按文件所屬組。
選項-mtime n 文件上次內容被修改距離現在n*24小時:
[root@centos7 temp]# ls -lt file1?-rw-r--r-- 1 root root 64 10月 27 15:06 file11-rw-r--r-- 1 root root 132 10月 27 13:28 file10-rw-r--r-- 1 root root 22 10月 26 21:31 file12-rw-r--r-- 1 root root 137 10月 12 16:42 file13[root@centos7 temp]# find . -name "file1?" -mtime +5 #五天前./file13[root@centos7 temp]# [root@centos7 temp]# find . -name "file1?" -mtime -5 #五天內./file10./file11[root@centos7 temp]#[root@centos7 temp]# find . -name "file1?" -mtime 5 #剛好五天./file12[root@centos7 temp]#
本例中使用了命令ls的選項-t對文件的時間進行排序,最近被修改的文件在前。選項-mtime n中n可以表示成:
+n 表示大于n
-n 表示小于n
n  表示等于n
還有其他時間(如atime,ctime)的比較,用法相同。
選項-newer file表示搜索到的文件比指定的file要‘新'(上次內容被修改離現在時間更短):
[root@centos7 temp]# find . -name "file1?" -newer file12./file10./file11[root@centos7 temp]#
選項-path pattern文件名匹配pattern(通配符):
[root@centos7 temp]# find . -name "file1?" -path "./file1[13]"./file11./file13[root@centos7 temp]#
新聞熱點
疑難解答