xargs 命令

例子

xargs 命令的原理比较简单,我举个例子就清楚了。

我需要查找当前目录下的所有 txt 文件,使用如下命令

$ find . -name '*.txt'
./person.txt
./quoted-strings.txt
./short-size.txt
./chapter-table.txt

现在我要通过 ls -l 命令查看所有这些 txt 文件的信息,那么我们肯定需要管道把 find 命令的结果传给 ls -l 命令。

然而,很遗憾,ls 命令不能接受标准输入,因此不能通过管道直接连接 findls 命令,因此下面的命令是错误的

$ # ls 不接受标准输入,因此这个命令是错误的
$ find . -name '*.txt' | ls -l

那么怎么办呢?要是我们能把 find 的命令结果的每一行作为 ls 命令作为参数,那不就完美了?xargs 命令的作用正好就是如此

$ # xargs 把 find 命令的结果的第一行,当作 ls -l 命令的参数
$ find . -name '*.txt' | xargs ls -l
-rw-r--r--  1 david  staff  109  1  5  2020 ./chapter-table.txt
-rw-r--r--  1 david  staff   57  1  4  2020 ./person.txt
-rw-r--r--  1 david  staff  121  1  7  2020 ./quoted-strings.txt
-rw-r--r--  1 david  staff    5 12 28  2019 ./short-size.txt

其实 xargs 命令有一个 -t 参数,可以在输出结果前,输出要执行的命令

$ xargs 命令的 -t 参数可以输出要执行的命令
$ find . -name '*.txt' | xargs -t ls -l
ls -l ./person.txt ./quoted-strings.txt ./short-size.txt ./chapter-table.txt
-rw-r--r--  1 david  staff  109  1  5  2020 ./chapter-table.txt
-rw-r--r--  1 david  staff   57  1  4  2020 ./person.txt
-rw-r--r--  1 david  staff  121  1  7  2020 ./quoted-strings.txt
-rw-r--r--  1 david  staff    5 12 28  2019 ./short-size.txt

看到了吧,find . -name '*.txt' | xargs -t ls -l 命令最终变为 ls -l ./person.txt ./quoted-strings.txt ./short-size.txt ./chapter-table.txt

官方说明

BSD 手册中,关于 xargs 命令,有一段描述如下

The xargs reads space, tab, newline and end-of-file delimited strings from the standard input and executes command with the strings as arguments.

现在明白了吧~

  • 6
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值