Linux 常用命令-grep, find, locate

349 阅读2分钟
  1. grep 命令:
    • 在单个文件中查找字符串:
      • grep "literal_string" fileName
        • 示例: grep "this" demo_file
    • 在多个文件查找字符串:
      • grep "string" fileNamePattern
        • 示例: grep "this" demo_*
    • 不区分大小写:
      • grep -i "literal_string" filename
        • 示例: grep -i "this" demo_file
    • 正则表达式查找:
      • grep "REGEX" filename
        • 示例: grep "lines.*empty" demo_file
    • 查找一个完整的单词, 而不是子串:
      • grep -w "literal_string" demo_file
        • 示例: grep -w "is" demo_file
    • 在当前文件下的所有文件中查找:
      • grep -r "literal_string"
        • 示例:grep -r "is"
    • 统计匹配数量:
      • grep -c "pattern" filename
        • 示例:grep -c "is" demo_file
    • 只显示匹配的文件名:
      • grep -l "pattern" filename
        • 示例:grep -l "is" demo_file
    • 显示匹配的行号:
      • grep -n "pattern" filename
        • 示例:grep -n "is" demo_file
  2. find 命令:
    • 在指定路径下查找:
      • find pathName -name fileName
        • 示例 find / -name mysqld.log
    • 在指定路径下查找, 不区分文件名大小写:
      • find pathName -iname fileName
        • 示例 find / -iname mysqld.log
    • 指定查找的深度深度:
      • find pathName -mindepth mindepth -maxdepth maxdepth -name fileName
        • 示例 find / -mindepth 2 -maxdepth 3 -name mysqld.log
    • 指定文件类型:
      • find pathName -name fileName -type typeName
        • 示例 find / -name test.txt -type -f
        • -type 含义:
          • b: 块设备文件
          • c: 字符设备文件
          • d: 目录文件
          • f: 普通文件
          • p: 管道文件
          • l: 符号链接
    • 指定文件大小:
      • find pathName -size fileSize
        • 查找大于 100 M文件: find / -size +100M
        • 查找小于 100 M文件: find / -size -100M
    • 根据 inode 号查找:
      • find -inum inodeNumber
        • 示例: find -inum 2165021
    • 指定日期范围内使用或修改的文件:
      • find / -name fileName -mtime n
        • 查找文件的修改时间距离当前时间超过 100 天: find / -mtime +100
        • -mtime 表示修改时间, -atime 表示访问时间
        • +n 表示超过, -n 表示未超过
    • 查找到文件后执行相应的命令:
      • find / -name fileName -exec command {} \;
        • 查找到文件后显示文件信息: find / -name test.txt -exec ls -l {} \;
    • 查找最大或最小的几个文件:
      • 查找最大的 5 个文件: find . -type f -exec ls -s {} \; | sort -n -r | head -5
      • 查找最小的 5 个文件: find . -type f -exec ls -s {} \; | sort -n | head -5
  3. locate 命令:
    • 查找文件: locate fileName
      • 示例: locate *.doc
        locate 是从建立的文件数据库中查找的, 有时候文件发生了改动, 例如文件已经删除了, 但是 locate 仍然会找到该文件, 这是因为文件数据库并没有更新. 若需要更新文件数据库, 需要使用 updatedb 命令.
  4. 参考:
    [1] : The Ultimate Tar Command Tutorial with 10 Practical Examples
    [2] : 15 Practical Linux Find Command Examples
    [3] : Linux从入门到精通(第2版)