find: 查找文件的利器

风行水上 @ 2011-10-25 09:24:28
标签:

    find是一个用来查找文件的shell命令。

    查找文件

    按文件大小来查找

    find . -type f -size +1M
    
    • -size用来指定要查找的文件的大小
      • "+1M"表示大于1MB,"-1M"表示小于1MB,"1M"表示等于1MB,没有"=1M"的写法。
      • 其他文件大小单位有:c(byte), b(512-byte blocks), k(kilobytes), M(Megabytes), G(Gigabytes)

    按文件日期来查找

    find . -type f -mtime +7 
    
    • -mtime用来测试文件最后修改时间,+7表示大于7天(24x7小时)
      • "n"表示介于区间[24*n,24*(n+1)]之间
      • "+n"表示大于n天(24*n小时)
      • "-n"表示小于n天(24*n小时)

    目录

    删除空的目录

    find . -depth -type d -empty -delete
    

    其中,

    • -depth指定深度优先以保证先删除子目录
    • -empty用来测试目录是否为空
    • -delete相当于-exec rm -rf {} \;

    跳过特定目录

    find $dir -name "*_GOLD" -prune -o -type f -name "*.tcl" -printf "%P\n"
    
    • -prune跳过匹配目录及其子目录
    • -o 逻辑或
    • -printf 不打印命令行中的目录名

    Misc

    查找包含指定字符串的文件

    find . -type f -exec grep -l "hello" {} \;
    

    主要是利用grep的"-l"选项。"-l"的作用是只列出匹配文件的文件名。

    如果要同时看到文件名和第一个匹配行,也可以用 grep -H -m 1 "hello"

    其实,grep命令提供了选项-r用于查找指定目录下的所有文件。我们也可以用下面的命令:

    grep -r -m 1 "hello"
    

    参考资源

    标签:

      分享到:
      comments powered by Disqus

      29/33ms