locate — 快速搜尋檔案路徑

從預建索引快速搜尋檔案路徑,速度遠快於 find。

語法

locate [選項] 樣式...

常用選項

選項 說明 範例
-i, --ignore-case 忽略大小寫 locate -i nginx.conf
-c, --count 只顯示符合的數量 locate -c "*.conf"
-l N, --limit 只顯示前 N 個結果 locate -l 10 config
-r, --regex 使用正規表示式搜尋 locate -r "\.py$"
-e, --existing 只顯示目前實際存在的檔案(跳過已刪除的) locate -e "*.log"
-n N 只輸出 N 個結果 locate -n 5 file

使用範例

範例 1:快速搜尋設定檔

搜尋系統中所有名為 nginx.conf 的檔案。

$ locate nginx.conf
/etc/nginx/nginx.conf
/usr/share/doc/nginx/nginx.conf
範例 2:忽略大小寫搜尋

搜尋時不區分大小寫,可同時找到 Makefile、makefile 等。

$ locate -i makefile
/home/user/project/Makefile
/usr/share/make/Makefile
範例 3:搜尋前先更新索引

剛建立的檔案不在索引中,需先用 updatedb 更新才能找到。

$ sudo updatedb
locate newfile.txt
/home/user/newfile.txt
範例 4:locate vs find 的速度比較

locate 查詢索引,幾乎瞬間回應;find 遍歷磁碟,較慢但結果即時。

$ time locate "*.conf" | wc -l
2847
real	0m0.021s

常見錯誤與排錯

locate: command not found
原因
mlocate(或 plocate)套件未安裝。
解法
sudo apt install mlocate(或 plocate)。
locate: /var/lib/mlocate/mlocate.db: No such file or directory
原因
資料庫尚未建立(安裝後第一次使用)。
解法
執行 sudo updatedb 建立索引資料庫,之後每日自動更新。

延伸閱讀