Bash命令使用find和siz排序对文件进行批处理

2024-06-01 08:49:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在寻找Linux命令,它按文件大小的升序批处理当前目录中的所有文件。你知道吗

作为一个具体的例子,myhello.py打印文件名:

print 'hello', sys.argv[1]

如果我的当前目录中有大小为(file1)<;=size(file2)<;=size(file3)的文件file1file2file3,那么应该输出我要查找的Linux命令

hello, file1
hello, file2
hello, file3

现在,我用

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

但我不知道如何处理文件的具体顺序对其大小。你知道吗?谢谢。你知道吗


Tags: 文件py命令lthellosizelinuxsys
1条回答
网友
1楼 · 发布于 2024-06-01 08:49:10

使用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 . -type f | xargs du | sort -n | cut -f 2 | xargs python hello.py

说明:

  1. du用文件大小进行注释
  2. sort按列大小排序
  3. cut删除额外大小的列,只保留第二列,即文件名
  4. xargs呼叫你好,派瑞在每条线上

使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 | ... 

相关问题 更多 >