zoukankan      html  css  js  c++  java
  • Linux命令之find

    find是一个使用非常频繁的命令。

    // 查找所有txt文件
    find . -name "*.txt"
    find . -name "*.txt" -ls
    // 查找所有txt文件和sh文件
    find . -name "*.txt" -o -name "*.sh"
    // 查找所有txt文件(搜索目标为文件)
    find . -type f -name "*.txt"
    // 查找所有目录
    find . -type d
    // 仅在当前目录和二级目录查找所有目录
    find . -maxdepth 2 -type d
    // 查找所有大小为0的文件并删除
    find . -type f -size 0 -delete
    // 跳过指定目录
    find . -path ./baddir -prune -o -name "*.txt" -print
    find . -type d ( -path dir1 -o -path dir2 -o -path dir3 ) -prune -o -name "*.txt" -print
    find -name "*.js" -not -path "./directory/*"

    基于文件时间的查找

    Linux下的每个文件有三种时间戳

    • atime,access time
    • mtime,modify time, 文件内容的修改
    • ctime,change time,文件权限或属性的修改

    find的一个重要参数:

    // 查找修改时间在指定日期之后的文件
    find . -type f -name "*.txt" -newermt 2017-08-02
    find . -type f -name "*.txt" -newermt "2017-08-02 12:00:00" 
    // 查找修改时间在指定日期之前的文件
    find . -type f -name "*.txt" ! -newermt 2017-08-02
    // 查找在指定日期修改的文件
    find . -type f -name "*.txt" -newermt 2017-08-02 ! -newermt 2017-08-03

    -exec

    // 删除所有大小为0的文件
    find . -type f -size 0 -exec rm {} ;

    对于每个匹配的文件,{}会被替换成相应的文件名,后面的 ; 要带上。

    -xargs

    xargs能够将标准输入数据转换成命令行参数。

    // 删除所有大小为0的文件
    find . -name "*.txt" -print0 | xargs -0 rm -f
    // 查找所有的txt和sh文件,结果按修改时间排序
    find . ( -name "*.txt" -o -name "*.sh" ) -print0 | xargs -0 ls -lt

    ls的-t参数,sort by modification time, newest first

    批量修改文件名

    #!/bin/bash
    
    filenames=($(find . -maxdepth 1 -name "*.txt"))
    
    for (( i = 0; i < ${#filenames[@]}; i++ ))
    do
        newname=$(printf 2017-08-02-%03d.txt $i)
        echo "rename ${filenames[$i]} to ${newname} ..."
        mv ${filenames[$i]} $newname
    done
    
    echo "done"

    参考资料:

    Exclude directory from find . command

  • 相关阅读:
    Centos7.3安装和配置Tomcat8
    Centos7.3安装和配置jre1.8
    -bash: /home/java/jdk1.8.0_221/bin/java: 权限不够
    Centos7安装vsftp服务
    CENTOS之文件搜索命令Find
    Centos之文件搜索命令locate
    DockerFile体系结构(保留字指令)
    DockerFile解析
    SpringBoot项目映射
    穿透,让你不再限制内网的约束【远程控制内网电脑】【3389端口】
  • 原文地址:https://www.cnblogs.com/gattaca/p/7272163.html
Copyright © 2011-2022 走看看