我正在寻找以文件大小的升序批量处理当前目录中所有文件的Linux命令。
作为具体示例,我的hello.py
打印文件名:
print 'hello', sys.argv[1]
如果我的当前目录包含文件file1
,file2
和file3
,其大小(file1)< = size(file2)< = size(file3),那么我正在寻找的Linux命令应该输出
hello, file1
hello, file2
hello, file3
目前,我使用
find . -type f -exec python hello.py {} \;
但是我没有看到如何按照特定顺序处理文件的大小。任何的想法?感谢。
答案 0 :(得分:4)
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 . -type f | xargs du | sort -n | cut -f 2 | xargs python hello.py
说明:
du
使用文件大小sort
按该尺寸列排序cut
删除额外的大小列,仅保留第二列,即文件名xargs
在每行调用hello.py # 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 | ...