天天看點

(0基礎學Linux系列)1.19 Linux檔案查找

1.1 find 指令介紹

find 是 Linux 中強大的搜尋指令,不僅可以按照檔案名搜尋檔案,還可以按照權限、大小、時間、inode 号等來搜尋檔案。

但是 find 指令是直接在硬碟中進行搜尋的,如果指定的搜尋範圍過大,find指令就會消耗較大的系統資源,導緻伺服器壓力過大。

是以,在使用 find 指令搜尋時,不要指定過大的搜尋範圍。

1.1.1 指令格式

find 搜尋路徑 [參數] 搜尋内容
           

1.1.2 指令參數

參數 作用
-name 按名字查找
-type 按檔案類型查找
-size [+-] 按檔案大小查找
-mtime [+-] 按修改時間查找
-exec 對查找的結果進行處理
-o 并集查找
-a 組合查找
! 取反

1.2 find 使用

1.2.1 -name 按照檔案名搜尋

1)使用文法:

# find 查找路徑 -name 查找内容
           

2)使用執行個體:

# 全名稱查找
find /root/ -name "oldboy.txt"

# 模糊查找
find /root/ -name "oldboy*"
           

1.2.2 -type 按檔案類型查找

1)檔案類型:

字元 檔案類型
f 普通檔案
d 目錄檔案
l 軟連接配接
c 字元裝置
b 塊檔案
c socket檔案

1)使用文法:

# find 查找路徑 -type 檔案類型字元
           

2)使用執行個體:

# 查找 /root/ 目錄下的目錄檔案
find /root/ -type d

# 查找 /root/ 目錄下的普通檔案
find /root/ -type f
           

1.2.3 -size [+-] 按檔案大小查找

1)檔案大小機關

機關 含義
b 按照 512 Byte 查找(預設機關)
c 按照位元組查找
k 按照KB機關搜尋
M 按照MB機關搜尋
G 按照GB機關搜尋

2)使用文法

# find 查找路徑 -size 檔案大小[大小機關]
           

3)使用執行個體:

# 按照位元組查找
find /root/ -size +1000c
find /root/ -size -1000c

# 按照KB機關查找
find /root/ -size +1k
find /root/ -size -1k

# 按照MB機關搜尋
find /boot/ -size +1M
find /root/ -size -1M

# 按照GB機關搜尋
find / -size +1G
find /root/ -size -1G
           

1.2.4 -mtime [+-] 按檔案修改時間查找

1)使用文法:

# find 查找路徑 -mtime [+-]天數
           

2)使用執行個體:

# 查找7天前修改過的檔案
find /root/ -mtime +7

# 查找7天内修改過的檔案
find /root/ -mtime -7

# 查找第7天修改過的檔案
find /root/ -mtime 7
           

1.2.5 -exec 對查找的結果進行處理

1)使用文法:

注意這裡的"{}"和";"是标準格式,隻要執行"-exec"選項,這兩個符号必須完整輸入

# find 查找路徑 [選項] 查找内容 -exec 指令2{}\;
           

2)使用執行個體:

# 建立一個空白且占500MB的檔案
dd if=/dev/zero of=test.log bs=1M count=500

# 删除 /root/ 目錄下大小為500MB的檔案
find /root/ -size 500M -exec rm -f {}\;
           

1.2.6 -o 并集查找

1)使用文法:

# find 查找路徑 [選項] 查找内容 -o [選項] 查找内容
           

2)使用執行個體:

# 查找檔案大小大于100MB的檔案,或者是目錄檔案
find /root/ -size +100M -o -type d
           

1.2.7 -a 組合查找

1)使用文法:

# find 查找路徑 [選項] 查找内容 -a [選項] 查找内容
           
# 查找檔案大小大于100MB的檔案,并且是普通檔案
find /root/ -size +100M -a -type f
           

1.2.8 ! 對查找的内容取反

# find 查找路徑 ! [選項] 查找内容
           
# 查找不小于100MB的檔案
find /root/ ! -size -100M
           

繼續閱讀