获取 xargs 到分词占位符 {}

mxx*_*xxk 5 bash xargs

(虽然分在 Bash 中有一个特定的定义,但在这篇文章中它的意思是在空格或制表符上进行拆分。)

使用此输入向 xargs 演示问题,

$ cat input.txt
LineOneWithOneArg
LineTwo WithTwoArgs
LineThree WithThree Args
LineFour  With  Double  Spaces
Run Code Online (Sandbox Code Playgroud)

和这个 Bash 命令回显传递给它的参数,

$ bash -c 'IFS=,; echo "$*"' arg0 arg1 arg2 arg3
arg1,arg2,arg3
Run Code Online (Sandbox Code Playgroud)

注意如何xargs -L1将每行单词拆分为多个参数。

$ xargs <input.txt -L1 bash -c 'IFS=,; echo "$*"' arg0
LineOneWithOneArg
LineTwo,WithTwoArgs
LineThree,WithThree,Args
LineFour,With,Double,Spaces
Run Code Online (Sandbox Code Playgroud)

但是,xargs -I{}将整行扩展{}为单个参数。

$ xargs <input.txt -I{} bash -c 'IFS=,; echo "$*"' arg0 {}
LineOneWithOneArg
LineTwo WithTwoArgs
LineThree WithThree Args
LineFour  With  Double  Spaces
Run Code Online (Sandbox Code Playgroud)

虽然在绝大多数情况下这是完全合理的行为,但有时xargs还是首选分词行为(第一个示例)。

虽然xargs -L1可以看作是一种解决方法,但它只能用于在命令行的末尾放置参数,从而无法表达

$ xargs -I{} command first-arg {} last-arg
Run Code Online (Sandbox Code Playgroud)

xargs -L1. (当然,除非command能够以不同的顺序接受参数,就像选项一样。)

有没有办法xargs -I{}在扩展{}占位符时对每一行进行分词?

web*_*ebb 5

有点。

echo -e "1\n2 3" | xargs sh -c 'echo a "$@" b' "$0"
Run Code Online (Sandbox Code Playgroud)

输出:

a 1 2 3 b
Run Code Online (Sandbox Code Playgroud)

参考:https ://stackoverflow.com/a/35612138/1563960

还:

echo -e "1\n2 3" | xargs -L1 sh -c 'echo a "$@" b' "$0"
Run Code Online (Sandbox Code Playgroud)

输出:

a 1 b
a 2 3 b
Run Code Online (Sandbox Code Playgroud)