Linux 檔案系統搜尋主要分兩類:依檔名找位置、在檔案中搜尋指定內容。以下簡介兩類搜尋方式。
查找檔案路徑可用 find、locate、whereis、which。
功能最強大靈活的檔案搜尋工具。
語法: find 路徑 -name 檔名
範例:在 /etc 搜尋 vsftpd.conf:
[root@localhost ~]# find /etc -name vsftpd.conf
詳細用法參考《Linux 檔案查找指令 find、xargs 詳述》。
透過檔名快速搜尋,使用前需建立索引資料庫。
步驟:
updatedb 建立索引:[root@localhost ~]# updatedb新裝軟體/新增檔案後必須重跑 updatedb 更新索引庫。
語法: locate 檔名
範例:查找 vsftpd.conf:
[root@localhost ~]# locate vsftpd.conf
/etc/vsftpd/vsftpd.conf
/home/beinan/vsftpd.conf
/root/.vsftpd.conf.swp
/root/vsftpd.conf
/root/vsftpd.config
/usr/share/doc/vsftpd-2.0.4/EXAMPLE/INTERNET_SITE/vsftpd.conf
/usr/share/doc/vsftpd-2.0.4/EXAMPLE/INTERNET_SITE_NOINETD/vsftpd.conf
/usr/share/doc/vsftpd-2.0.4/EXAMPLE/VIRTUAL_USERS/vsftpd.conf
/usr/share/logwatch/default.conf/logfiles/vsftpd.conf
/usr/share/logwatch/default.conf/services/vsftpd.conf
/usr/share/man/man5/vsftpd.conf.5.gz
搜尋指令二進制檔,同時找對應說明文件。
範例: whereis fdisk → fdisk: /sbin/fdisk /usr/share/man/man8/fdisk.8.gz
whereis grub → grub: /sbin/grub /etc/grub.conf /usr/share/grub /usr/share/man/man8/grub.8.gz
僅在 PATH 環境變數路徑搜尋指令。
範例: which fdisk → /sbin/fdisk
管理伺服器常需查日誌/指令輸出並篩選內容。結合 cat、grep、egrep、more 及管線 | 完成,輸出到檔用 >。
範例:查 /var/log/messages 擷取含 "May 8" 的行:
[root@localhost ~]# cat /var/log/messages | grep 'May 8' | more
注意:May 和 8 有空格,需單引號括起搜尋字串。
輸出到檔:
[root@localhost ~]# cat /var/log/messages | grep 'May 8' > ~/message0508.txt
[root@localhost ~]# more ~/message0508.txt
流程:cat 看內容 → grep 擷取含 "May 8" 的行 → > 輸出至家目錄 message0508.txt → more 看檔案。
從指令輸出中搜尋:
直接從指令輸出篩選,例:
[root@localhost ~]# ls -lh
總計 24M
-rwxr-xr-x 1 root root 545 04-25 11:21 adduml02.sh
-rwxr-xr-x 1 root root 545 2004-01-18 adduml.sh
-rw-rw-rw- 1 root root 0 04-25 14:26 dood
drwxr-xr-t 2 root root 4.0K 04-24 21:59 googledir
(可接 | grep 關鍵字 進一步篩選)