Bash命令使用find批量处理文件并按大小排序

时间:2015-12-24 04:52:15

标签: python linux bash

我正在寻找以文件大小的升序批量处理当前目录中所有文件的Linux命令。

作为具体示例,我的hello.py打印文件名:

print 'hello', sys.argv[1]

如果我的当前目录包含文件file1file2file3,其大小(file1)< = size(file2)< = size(file3),那么我正在寻找的Linux命令应该输出

hello, file1
hello, file2
hello, file3

目前,我使用

find . -type f -exec python hello.py {} \;

但是我没有看到如何按照特定顺序处理文件的大小。任何的想法?感谢。

1 个答案:

答案 0 :(得分:4)

使用ls

ls可以使用-S开关

轻松按大小排序
for x in $(ls -S); do                    
    python hello.py $x
done

或作为单行:for x in $(ls -S); do python hello.py $x; done

或者使用xargs,如下所示:ls -1 -S | xargs -n 1 python hello.py,但要小心,因为这会将文件名中的空格分成多个文件,更多内容在下面*

使用find而不更改hello.py

find . -type f | xargs du | sort -n | cut -f 2 | xargs python hello.py

说明:

  1. du使用文件大小
  2. 进行注释
  3. sort按该尺寸列排序
  4. cut删除额外的大小列,仅保留第二列,即文件名
  5. xargs在每行调用hello.py
  6. 使Python脚本接受管道

    # hello.py
    import sys
    
    def process(filename):
        print 'hello ', filename
    
    if __name__ == '__main__':
        for filename in sys.stdin.readlines():
            process(filename)
    

    现在您可以将输出传输到它,例如:

    find . -type f | xargs du | sort -n | cut -f 2 | python hello.py
    

    *如果你需要支持包含空格的文件名,我们应该使用0个终止行,所以:

    find . -type f -print0 | xargs -0 du | ...