删除所有特定大小的文件

Alg*_*Man 5 python shell perl

我有一堆日志文件,我必须删除一些小尺寸的文件,这些文件是创建的错误文件.(63字节).我只需要复制那些包含数据的文件.

Wri*_*ken 18

Shell(linux);

find . -type f -size 63c -delete
Run Code Online (Sandbox Code Playgroud)

将遍历子目录(除非你另有说明)

  • @Wrikken:并非所有版本的`find`都默认为当前目录.最好明确指定目录,以避免以后意外失败的命令. (4认同)
  • 啊?我不会问哪个版本/平台?并不是说明确有什么不对,特别是在删除时,只是好奇. (2认同)
  • @Wrikken:GNU find是我所知道的唯一默认为"."的人.BSD派生的版本往往需要path参数.我碰巧有一台OSF/1机器也需要路径参数. (2认同)

zif*_*fot 11

由于您使用"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)
Run Code Online (Sandbox Code Playgroud)


Cha*_*ens 5

Perl one衬里是

perl -e 'unlink grep {-s == 63} glob "*"'
Run Code Online (Sandbox Code Playgroud)

虽然,在运行它之前测试它会做什么总是一个好主意:

perl -le 'print for grep {-s == 63} glob "*"'
Run Code Online (Sandbox Code Playgroud)

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

#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}, "."'
Run Code Online (Sandbox Code Playgroud)

我使用需要$File::Find::name在发现版本,所以你得到整个路径,因为取消链接的版本并不需要它File::Find改变目录到每个目标目录,并设置$_为文件名(这是怎么-sunlink获取文件名).你可能也想查找grepglob