我注意到今天Bash printf有一个-v选择
-v var assign the output to shell variable VAR rather than
display it on the standard output
Run Code Online (Sandbox Code Playgroud)
如果我这样调用就行了
$ printf -v var "Hello world"
$ printf "$var"
Hello world
Run Code Online (Sandbox Code Playgroud)
来自管道它不起作用
$ grep "Hello world" test.txt | xargs printf -v var
-vprintf: warning: ignoring excess arguments, starting with `var'
$ grep "Hello world" test.txt | xargs printf -v var "%s"
-vprintf: warning: ignoring excess arguments, starting with `var'
Run Code Online (Sandbox Code Playgroud)
xargs将调用/usr/bin/printf(或在您的系统上安装该二进制文件的任何位置).它不会调用bash的内置函数.只有内置(或采购脚本或类似)才能修改shell的环境.
即使它可以调用bash的内置xargs函数,你的示例中也会运行一个子集.无论如何,子shell无法修改它的父级环境.所以你正在尝试的东西是行不通的.
如果我理解你的样品,我会看到一些选项; 样本数据:
$ cat input
abc other stuff
def ignored
cba more stuff
Run Code Online (Sandbox Code Playgroud)
简单的变量(根据你想要的东西有点棘手):
$ var=$(grep a input)
$ echo $var
abc other stuff cba more stuff
$ echo "$var"
abc other stuff
cba more stuff
Run Code Online (Sandbox Code Playgroud)
如果您想在数组中使用单个单词,请使用数组:
$ var=($(grep a input))
$ echo "${var[0]}"-"${var[1]}"
abc-other
Run Code Online (Sandbox Code Playgroud)
或者如果你想要每个数组元素中的整行:
$ IFS=$'\n' var=($(grep a input)) ; unset IFS
$ echo "${var[0]}"-"${var[1]}"
abc other stuff-cba more stuff
Run Code Online (Sandbox Code Playgroud)