shell端查找和搜索:which, whereis, locate, find and grep

简单总结一下shell经常使用的文件查找和内容搜索工具.java

which

能够查找执行文件的路径,例如:
正则表达式

-bash-4.3$ which ifconfig
/sbin/ifconfig
-bash-4.3$ which ls
alias ls='ls --color=auto'
        /bin/ls

whereis and locate

用于文件名的查找。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

find

速度较慢可是功能强大。下面分几个不一样的功能来介绍此命令: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

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
相关文章
相关标签/搜索