【问题标题】:Bash command to batch-process files using find and sorted by sizeBash 命令使用 find 批处理文件并按大小排序
【发布时间】:2015-12-24 22:13:58
【问题描述】:

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

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

print 'hello', sys.argv[1]

如果我的当前目录有文件file1file2file3,大小(file1)

hello, file1
hello, file2
hello, file3

目前,我使用

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

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

【问题讨论】:

  • 仅供参考,没有“Linux 命令”之类的东西。您在 shell(例如 Bash)中调用的东西要么是程序(如 /bin/ls),要么是 shell 命令(如 cd)。因此,您应该始终提及您正在使用的实际 shell,因为它们之间的语法差异有时很重要。

标签: python linux bash


【解决方案1】:

使用 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. sort 按该大小列排序
  3. cut 删除了额外的大小列,只保留第二列,即文件名
  4. xargs 在每一行调用 hello.py

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

【讨论】:

  • 是否有可能坚持“查找”,并使用管道?
  • "ls -1 -S | xargs -n 1 hello.py" 应该完成这项工作吗?也许用 ls 的 -R 开关?
  • 当然,但我认为他想继续使用find
  • 感谢您的详细解答!
猜你喜欢
  • 1970-01-01
  • 2017-02-03
  • 2016-06-10
  • 1970-01-01
  • 2015-05-03
  • 1970-01-01
  • 1970-01-01
  • 2020-08-02
  • 2016-02-23
相关资源
最近更新 更多