xargs command

xargs 命令应该紧跟在管道操作符之后。它使用标准输入作为主要的数据源,将从 stdin 中读取的数据作为指定命令的参数并执行该命令。

例如:
在一组 C 语言源码文件中搜索自负串main:
ls *.c | sargs grep main

Example 1: 将多行输入 –> 单行输出

1
2
3
4
5
6
7
➜   cat example.txt
1 2 3 4
5 6
7 8 9
10 11
➜ cat example.txt | xargs
1 2 3 4 5 6 7 8 9 10 11

Example 2: 将单行输入 –> 多行输出

xargs 的 -n 选项可以限制每次调用命令时用到的参数个数。

1
2
3
4
5
➜   cat example.txt | xargs -n  3
1 2 3
4 5 6
7 8 9
10 11

工作原理:
xargs 命令接收来自stdin的输入,将数据解析成单个元素,然后调用指定命令讲这些元素作为该命令的参数。xargs 默认使用 空白字符 分割输入并执行 /bin/echo

Example 3: 自定义分隔符 -d 选项

1
2
echo "splitXsplit1Xsplit2Xsplit3" | xargs -d X
split split1 split2 split3

Example 4: 结合find使用xargs

find . -type f -name "*.txt" -print0 | xargs -o grep -L image

如果文件系统的有些文件名中包含忠哥,find 命令的 -print0 选项可以使用0(NUL)来分割查找到的元素,然后再用xargs对应的-0选项进行解析

反例:
$find . -type f -name "*.txt" -print | xargs rm -f
这样做很危险,由可能会误删除文件。我们无法预测 find命令输出的分隔符究竟是什么(究竟是‘\n’还是 ‘’)。如果由文件名中包含空格符(‘ ’ ),xargs会将其误认为是分隔符。例如, bashrc text.txt 会被是为 bashrc 和 text.txt 。因此上面的命令不会删除 bashrc text.txt ,而是会把 bashrc删除

正确的姿势:
$find . -type f -name "*.txt" -print0 | xargs -0 rm -f

注意事项

docker ps -a -q | xargs --no-run-if-empty docker rm -f

参数 --no-run-if-empty 可以避免在前面的命令完全没有输出的情况下执行该命令

Donate
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.
  • Copyrights © 2019-2024 John Doe
  • Visitors: | Views:

请我喝杯咖啡吧~