【问题标题】:How to perform multiple commands on a list of files in bash (xargs?)如何在bash(xargs?)中的文件列表上执行多个命令
【发布时间】:2017-03-12 17:32:57
【问题描述】:

我有一个包含文件列表的文件,我想对每个文件执行两个命令。

files.txt 的内容:

file1
file2
file3

我想对每个文件执行的命令是(例如)ls -sdu

我希望输出最终是这样的:

<ls size> <du size> file1
<ls size> <du size> file2
<ls size> <du size> file3

我知道如何使用 bash 脚本来做到这一点,但有没有办法通过进程替换或其他方式轻松地在一行上做到这一点?

我以为我可以做这样的事情,但是没有用:

cat files.txt | tr '\n' '\0' | xargs -0 -I{} cat <(du {} ) <(ls -s {})

出现了这些错误:

du: cannot access `{}': No such file or directory
ls: cannot access {}: No such file or directory

有没有办法做到这一点?

【问题讨论】:

    标签: bash xargs command-substitution process-substitution


    【解决方案1】:

    您可以运行shxargs,其中可以放置多个命令,例如:

    xargs -0 -I{} sh -c 'du {}; ls -s {}'
    

    【讨论】:

    • 谢谢!好的,我的后续问题是,我想让du 只在行前加上它的测量大小。通常的方法是使用du &lt;filename&gt; | cut -f1 | tr --delete '\n',但我不能使用单引号,因为sh 命令是使用单引号引起来的。有什么办法可以代替du 部分吗?
    • 你可以用双引号引用。
    • 有没有办法将其转义,以便文件名可以包含单引号或双引号?
    • @localhost 是的,使用包装脚本,而不是 sh -c '...'。例如xargs -0 -I{} wrapper.sh {}。在这种形式下,shell 将正确地转义{} 中的文件名,并且wrapper.sh 可以与"$1" 一起使用,如du "$1"; ls -s "$1"
    猜你喜欢
    • 2011-11-20
    • 1970-01-01
    • 1970-01-01
    • 2012-09-17
    • 2017-04-03
    • 1970-01-01
    • 2016-08-11
    • 2019-12-07
    • 2023-03-11
    相关资源
    最近更新 更多