【问题标题】:deleting all the file of certain size删除所有一定大小的文件
【发布时间】:2011-02-28 22:59:46
【问题描述】:

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

【问题讨论】:

    标签: python perl shell


    【解决方案1】:

    壳牌(Linux);

    find . -type f -size 63c -delete
    

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

    【讨论】:

    • ~unutbu 可以添加目录,但不需要(默认为工作目录),尽管可以很好地说明可以给出多个路径:find ./foo/bar ./foz ../../baz -type f 将同时搜索所有 3 个目录。
    • @Wrikken:并非所有版本的find 都默认为当前目录。最好明确指定目录以避免以后意外失败的命令。
    • 啊?我不能问哪个版本/平台?并不是说显式有什么问题,尤其是在删除时,只是好奇。
    • @Wrikken:GNU find 是我所知道的唯一一个默认为“。”的人; BSD 派生的版本往往需要路径参数。我碰巧有一台 OSF/1 机器,它也需要一个路径参数。
    【解决方案2】:

    由于您用“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)
    

    【讨论】:

      【解决方案3】:

      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

      【讨论】:

        猜你喜欢
        • 2015-01-20
        • 2018-08-02
        • 1970-01-01
        • 2012-04-12
        • 1970-01-01
        • 2012-02-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多