linux find 命令的使用/find 删除文件

一、背景

find命令是一个linux 常用的命令,作用是查找文件。由于对于查找文件需求的多样性,find 的使用实际上是非常复杂的,因此本文记录一下 find 命令的使用,方便自己查阅。

一些参考:
find 的基础用法
find 的 35 种命令

二、具体代码

2.1 查找文件

# Find all directories named src
find . -name src -type d
# Find all python files that have a folder named test in their path
find . -path '*/test/*.py' -type f
# Find all files modified in the last day
find . -mtime -1
# Find all zip files with size in range 500k to 10M
find . -size +500k -size -10M -name '*.tar.gz'

# Delete all files with .tmp extension
find . -name '*.tmp' -exec rm {} \;
# Find all PNG files and convert them to JPG
find . -name '*.png' -exec convert {} {}.jpg \;

2.2 查找并删除文件

使用背景:希望使用find命令进行模糊查找,并删除匹配到的文件。
注意:小心小心再小心,可能会匹配到意想不到的文件,但是有没有注意到,从而被删除

find . -name "FILE-TO-FIND" -exec rm -rf {} \;

重点:不要少分号、不要少空格,不然会报错

三、