linux根据单词查找文件

1、根据某单词查找

grep -rn "hello,world!" *

* : 表示当前目录所有文件,也可以是某个文件名

-r 是递归查找

-n 是显示行号

-R 查找所有文件包含子目录

-i 忽略大小写

grep -i pattern files :不区分大小写地搜索。默认情况区分大小写, 

grep -l pattern files :只列出匹配的文件名, 

grep -L pattern files :列出不匹配的文件名, 

grep -w pattern files :只匹配整个单词,而不是字符串的一部分(如匹配‘magic’,而不是‘magical’), 

grep -C number pattern files :匹配的上下文分别显示[number]行, 

grep pattern1 | pattern2 files :显示匹配 pattern1 或 pattern2 的行, 

grep pattern1 files | grep pattern2 :显示既匹配 pattern1 又匹配 pattern2 的行。

\< 和 \> 分别标注单词的开始与结尾。

例如: 

grep man * 会匹配 ‘Batman’、‘manic’、‘man’等, 

grep '\<man' * 匹配‘manic’和‘man’,但不是‘Batman’, 

grep '\<man\>' 只匹配‘man’,而不是‘Batman’或‘manic’等其他的字符串。 

'^':指匹配的字符串在行首, 

'$':指匹配的字符串在行尾,  

2,xargs配合grep查找

find -type f -name '*.php'|xargs grep 'GroupRecord'

3、locate

locate filename:搜索文件和目录的名称
locate -i filename:不区分大小写的搜索文件名和目录

4、grep

grep want_to_find filename:搜索文件总包含想找的单词

want_to_find 单词中间有特殊符号的时候,可以加’’,告诉shell正在搜索一个字符串,使用""则表示要使用shell变量

grep -R want_to_find *:搜索多个目录的结果

grep -R want_to_find * > want_to_find .txt:把搜索的过多的结果放到want_to_find.txt中

grep -R want_to_find * --color=auto:把搜索出来的单词变成彩色

grep -i want_to_find *:找出不区分大小写的单词

grep -w want_to_find *:在文件中搜索完整的单词

grep -n want_to_find *:显示搜索单词在文件的行数

tail info.log | grep -B 3 "want_to_find " --color=auto 找含有want_to_find 字符的哪一行的前3行(before)

tail info.log | grep -A 3 "want_to_find " --color=auto 找含有want_to_find 字符的哪一行的后3行(after)

tail info.log | grep -C 3 "want_to_find " --color=auto 找含有want_to_find 字符的前后的完整的上下文信息(context)

ls -l | grep -n want_to_find --color=auto 可以把找到的含有want_to_find 字符的那一行的行号打印出来

ls -l | grep -v do_not_want_to_find 可以把不含有do_not_want_to_find 的结果打印出来

grep -il -l want_to_find filename_path/* 可以把含有do_not_want_to_find 的文件名称打印出来

grep -c 广告 info.log 把info.log中出现的广告的次数打印出来

ls -l | grep 196[6-7] | grep -v live 在某个搜索结果中搜索单词

5.find命令

    基本格式:find  path expression

    1.按照文件名查找

    (1)find / -name httpd.conf  #在根目录下查找文件httpd.conf,表示在整个硬盘查找
    (2)find /etc -name httpd.conf  #在/etc目录下文件httpd.conf
    (3)find /etc -name '*srm*'  #使用通配符*(0或者任意多个)。表示在/etc目录下查找文件名中含有字符串‘srm’的文件
    (4)find . -name 'srm*'   #表示当前目录下查找文件名开头是字符串‘srm’的文件

    2.按照文件特征查找     

    (1)find / -amin -10   # 查找在系统中最后10分钟访问的文件(access time)
    (2)find / -atime -2   # 查找在系统中最后48小时访问的文件
    (3)find / -empty   # 查找在系统中为空的文件或者文件夹
    (4)find / -group cat   # 查找在系统中属于 group为cat的文件
    (5)find / -mmin -5   # 查找在系统中最后5分钟里修改过的文件(modify time)
    (6)find / -mtime -1   #查找在系统中最后24小时里修改过的文件
    (7)find / -user fred   #查找在系统中属于fred这个用户的文件
    (8)find / -size +10000c  #查找出大于10000000字节的文件(c:字节,w:双字,k:KB,M:MB,G:GB)
    (9)find / -size -1000k   #查找出小于1000KB的文件

    3.使用混合查找方式查找文件

    参数有: !,-and(-a),-or(-o)。

    (1)find /tmp -size +10000c -and -mtime +2   #在/tmp目录下查找大于10000字节并在最后2分钟内修改的文件
         (2)find / -user fred -or -user george   #在/目录下查找用户是fred或者george的文件文件
         (3)find /tmp ! -user panda  #在/tmp目录中查找所有不属于panda用户的文件

猜你喜欢

转载自www.cnblogs.com/yaradish/p/10576330.html