例子
xargs 命令的原理比较简单,我举个例子就清楚了。
我需要查找当前目录下的所有 txt 文件,使用如下命令
$ find . -name '*.txt'
./person.txt
./quoted-strings.txt
./short-size.txt
./chapter-table.txt
现在我要通过 ls -l
命令查看所有这些 txt 文件的信息,那么我们肯定需要管道把 find
命令的结果传给 ls -l
命令。
然而,很遗憾,ls 命令不能接受标准输入,因此不能通过管道直接连接 find
和 ls
命令,因此下面的命令是错误的
$ # 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.
现在明白了吧~