簡單總結一下shell經常使用的文件查找和內容搜索工具.java
能夠查找執行文件的路徑,例如:
正則表達式
-bash-4.3$ which ifconfig /sbin/ifconfig -bash-4.3$ which ls alias ls='ls --color=auto' /bin/ls
用於文件名的查找。find命令相對較慢,這兩個命令利用數據庫(Linux系統會將全部的文件記錄在一個數據庫文件裏面)來查找數據,至關快速,找不到時再用find。shell
whereis 查找特定文件,例如:數據庫
-bash-4.3$ whereis profile profile: /etc/profile.d /etc/profile /usr/include/profile.h -bash-4.3$ whereis vimrc vimrc: /etc/vimrc
locate能夠經過文件的部分名稱來查找,命令示例如:vim
locate [-ir] keywork # i:ignore ; r: regular -bash-4.3$ locate vimrc /etc/vimrc /etc/libreport/events/collect_vimrc_system.xml /etc/libreport/events/collect_vimrc_user.xml /etc/libreport/events.d/vimrc_event.conf -bash-4.3$ locate ifconfig /sbin/ifconfig /usr/libexec/hypervkvpd/hv_set_ifconfig /usr/sbin/pifconfig
locate查找的是已建立的數據庫:/var/lib/mlocate,此數據庫默認天天建立一次,能夠用「updatedb」手動更新。bash
速度較慢可是功能強大。下面分幾個不一樣的功能來介紹此命令:socket
命令格式: 工具
find [PATH] [option] [action]
1. 時間參數ui
-mtime n: n天以前的「一天以內」改過的文件 -mtime +n: n天以前改過的文件 -mtime -n: n天以內改過的文件 -newer file: 與已存在的file相比還要新的文件,比較新舊文件時有用
2. 用戶和用戶組this
-uid n: n = UID, records in /etc/passwd -gid n: n = GID, records in /etc/group -user name -group name -nouser: find file belongs to none of user in /etc/passwd -nogroup -bash-4.3$ find temp/ -user ancient_wind temp/ temp/predixDoc.tar temp/newfile temp/newfile2
3. 文件權限及名稱
-name filename: filename能夠用通配符 -size [+-]SIZE: for SIZE, c=byte, k=1024bytes -type TYPE: f=file, d=folder, b/c=device, l=link, s=socket, p=FIFO -perm [+-]mode: mode is like the value of chmod, perm=permission
4. 其餘功能
find的特殊功能是可以進行額外的動做(action)
-exec command -print: this is a default action -bash-4.3$ find / -perm +7000 -exec ls -l {} \; 此例中,find的結果放到{}中,\轉義符,位於-exec到;之間的就是action。
grep是一個更增強大的文件/內容搜索工具,常配合管道使用。基本語法以下:
[root@www ~]# grep [-acinv] [--color=auto] 「keywords」 filename 選項與參數: -a :將 binary 文件以 text 文件的方式搜尋數據 -c :計算找到 '搜尋字符串' 的次數 -i :忽略大小寫的不一樣,因此大小寫視爲相同 -n :順便輸出行號 -v :反向選擇,亦即顯示出沒有 '搜尋字符串' 內容的那一行! --color=auto :能夠將找到的關鍵詞部分加上顏色的顯示喔!
搜索關鍵字可以使用正則表達式。
1. 目錄下搜素文件名包含某字符的文件 find ~/tmp -name "[Ss]hell*" 2. 搜素子目錄下包含特定內容的文件 grep -r "key" dir grep -R --include="*.java" 「key」 dir 3. 搜索空白行 grep -n "^&" file 4. 搜索以小數點結尾的行 grep -n "\.&" file