如何将命令输出的第二行读入 bash 变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13624774/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 03:53:16  来源:igfitidea点击:

How to I read the second line of the output of a command into a bash variable?

bash

提问by sorin

I have a command that prints several lines and I do want to put the second line into a bash variable.

我有一个打印多行的命令,我确实想将第二行放入 bash 变量中。

like echo "AAA\nBBB"and I want a bash command that would put BBBin a bash variable.

喜欢echo "AAA\nBBB",我想要一个 bash 命令,它会放入BBB一个 bash 变量。

回答by Steve

With sed:

sed

var=$(echo -e "AAA\nBBB" | sed -n '2p')

With awk:

awk

var=$(echo -e "AAA\nBBB" | awk 'NR==2')

Then simply, echo your variable:

然后简单地,回显你的变量:

echo "$var"

回答by Aaron Digulla

Call readtwice:

调用read两次:

echo -e "AAA\nBBB" | { read line1 ; read line2 ; echo "$line2" ; }

Note that you need the {}so make sure both commands get the same input stream. Also, the variables aren't accessible outside the {}, so this does notwork:

请注意,您需要{}确保两个命令获得相同的输入流。此外,变量是无法访问外{},因此这并不会工作:

echo -e "AAA\nBBB" | { read line1 ; read line2 ; } ; echo "$line2"

回答by P.P

You can use sed:

您可以使用sed

SecondLine=$(Your_command |sed -n 2p)

For example:

例如:

 echo -e "AAA\nBBBB" | sed -n 2p

You change the number according to the line you want to print.

您可以根据要打印的行更改数字。

回答by Lars Kotthoff

You can do this by piping the output through head/tail -- var=$(cmd | tail -n +2 | head -n 1)

您可以通过通过 head/tail 管道输出来做到这一点 - var=$(cmd | tail -n +2 | head -n 1)

回答by koola

Use an array with parameter expansion to avoid subshells:

使用带参数扩展的数组来避免子shell:

str="AAA\nBBB"
arr=(${str//\n/ })
var="${arr[1]}"
echo -e "$str"

回答by Tyzoid

in a bash script: Variable=echo "AAA\nBBB" | awk "NR==2"

在 bash 脚本中:Variable=echo "AAA\nBBB" | awk "NR==2"

回答by Chris Seymour

Like this:

像这样:

var=$(echo -e 'AAA\nBBB' | sed -n 2p)
echo $var
BBB