xargs擅长插入初始参数:
seq 0 10 | xargs -n 3 echo foo
Run Code Online (Sandbox Code Playgroud)
产生以下输出:
foo 0 1 2
foo 3 4 5
foo 6 7 8
foo 9 10
Run Code Online (Sandbox Code Playgroud)
当我还想要尾随参数时该怎么办?也就是说,什么命令:
seq 0 10 | xargs -n 3 <WHAT GOES HERE?>
Run Code Online (Sandbox Code Playgroud)
将产生以下期望的输出:
foo 0 1 2 bar
foo 3 4 5 bar
foo 6 7 8 bar
foo 9 10 bar
Run Code Online (Sandbox Code Playgroud)
我尝试了以下方法:
seq 0 10 | xargs -n 3 -I {} echo foo {} bar
Run Code Online (Sandbox Code Playgroud)
这几乎是正确的,除了它显然在每个命令行中强制使用一项,这不是我想要的:
foo 0 bar
foo 1 bar
foo 2 bar
foo 3 bar
foo 4 bar
foo 5 bar
foo 6 bar
foo 7 bar
foo 8 bar
foo 9 bar
foo 10 bar
Run Code Online (Sandbox Code Playgroud)
在从@netniV 的回答中抢先弄清楚这一点之后,我现在看到手册页实际上包含一个示例,展示了如何做到这一点:
Run Code Online (Sandbox Code Playgroud)xargs sh -c 'emacs "$@" < /dev/tty' emacs一个接一个地启动所需的最少 Emacs 副本,以编辑 xargs 标准输入中列出的文件。这个例子实现了与 BSD 的 -o 选项相同的效果,但以更灵活和可移植的方式。
和维基百科页面显示了类似的技术,并在最后的虚拟arg的解释:
实现类似效果的另一种方法是使用 shell 作为启动命令,并处理该 shell 中的复杂性,例如:
Run Code Online (Sandbox Code Playgroud)$ mkdir ~/backups $ find /path -type f -name '*~' -print0 | xargs -0 bash -c 'for filename; do cp -a "$filename" ~/backups; done' bash行尾的单词
bash被解释bash -c为特殊参数$0。如果 bash 一词不存在,则第一个匹配文件的名称将被分配给,$0并且该文件不会被复制到~/backups. 可以使用任何单词代替bash,但由于$0通常扩展为正在执行的 shell 或 shell 脚本的名称,因此bash是一个不错的选择。
所以,这是如何做到的:
seq 0 10 | xargs -n 3 sh -c 'echo foo "$@" bar' some_dummy_string
Run Code Online (Sandbox Code Playgroud)
输出符合要求:
foo 0 1 2 bar
foo 3 4 5 bar
foo 6 7 8 bar
foo 9 10 bar
Run Code Online (Sandbox Code Playgroud)
使用xargs的-i参数,例如:
ls -1 | xargs -t -i echo "Found {} file"
Run Code Online (Sandbox Code Playgroud)
请注意,-t仅用于显示将要发出的命令。实时运行时,请不要使用-t参数。
该{}由实际参数所取代。请注意,这确实意味着每个文件每个命令只能运行一次。不作为一组文件。如果需要使用其他替换字符串,请在-i之后指定它
ls -1 | xargs -t -i[] xargs echo "Found []{} file"
Run Code Online (Sandbox Code Playgroud)
将保留{}在文件名之后,该文件名在出现[]
创建一个名为runme.sh的脚本文件
#!/bin/sh
echo "foo $@ bar"
Run Code Online (Sandbox Code Playgroud)
确保chmod + X然后使用
seq 0 10 | xargs -n 3 ./runme.sh
Run Code Online (Sandbox Code Playgroud)
这会产生
foo tests tree.php user_admin.php bar
foo user_domains.php user_group_admin.php utilities.php bar
foo vdef.php bar
Run Code Online (Sandbox Code Playgroud)