删除特定大小的所有文件

4 投票
3 回答
3547 浏览
提问于 2025-04-15 23:40

我有一堆日志文件,需要删除一些小文件,这些小文件是错误生成的,大小只有63字节。我只想保留那些里面有数据的文件。

3 个回答

6

这个 Perl 的一行代码是:

perl -e 'unlink grep {-s == 63} glob "*"'

不过,在运行之前,先测试一下它会做什么总是个好主意:

perl -le 'print for grep {-s == 63} glob "*"'

如果你想遍历整个目录树,你需要不同的版本:

#find all files in the current hierarchy that are 63 bytes long.
perl -MFile::Find=find -le 'find sub {print $File::Find::name if -s == 63}, "."'

#delete all files in the current hierarchy that 63 bytes long
perl -MFile::Find=find -e 'find sub {unlink if -s == 63}, "."'

我在查找的版本中使用了 $File::Find::name,这样你就能得到完整的路径,而在删除的版本中就不需要这个,因为 File::Find 会进入每个目标目录,并把 $_ 设置为文件名(这就是 -sunlink 如何获取文件名的方式)。你可能还想了解一下 grepglob

10

因为你在问题中标记了“python”,所以这里有一种在这个语言中实现的方法:

target_size = 63
import os
for dirpath, dirs, files in os.walk('.'):
    for file in files: 
        path = os.path.join(dirpath, file)
        if os.stat(path).st_size == target_size:
            os.remove(path)
19

Shell(Linux);

find . -type f -size 63c -delete

它会自动遍历子目录(除非你特别指示它不要这样做)

撰写回答