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

转载于:https://www.cnblogs.com/gattaca/p/7272163.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值