Bash 从变量中获取最后一行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39615142/
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-08 22:25:39  来源:igfitidea点击:

Bash get last line from a variable

bashvariablesline

提问by Matt Backslash

If I have a variable with multiple lines (text) in it, how can I get the last line out of it?

如果我有一个包含多行(文本)的变量,我怎样才能从中取出最后一行?

I already figured out how to get the first line:

我已经想出了如何获得第一行:

STRING="This is a
multiple line
variable test"
FIRST_LINE=(${STRING[@]})
echo "$FIRST_LINE"

# output:
"This is a"

Probably there should be an operator for the last line. Or at least I assume that because with @the first line comes out.

可能最后一行应该有一个运算符。或者至少我认为这是因为@第一行出来了。

回答by redneb

An easy way to do this is to use tail:

一个简单的方法是使用tail

echo "$STRING" | tail -n1

回答by anubhava

Using bash string manipulations:

使用 bash 字符串操作:

$> str="This is a
multiple line
variable test"

$> echo "${str##*$'\n'}"
variable test

${str##*$'\n'}will remove the longest match till \nfrom start of the string thus leaving only the last line in input.

${str##*$'\n'}将删除最长的匹配直到\n从字符串的开头,从而只留下输入中的最后一行。

回答by chepner

If you want an array with one element per line from STRING, use

如果您想要一个每行一个元素的数组 from STRING,请使用

readarray -t lines <<< "$STRING"

Then, the first line would be ${lines[0]}, and the last line would be ${lines[-1]}. In older versions of bash, negative indices aren't allowed and you'll have to compute the last index manually: ${lines[${#lines[@]}-1]}.

然后,第一行是${lines[0]},最后一行是${lines[-1]}。在旧版本的 中bash,不允许使用负索引,您必须手动计算最后一个索引:${lines[${#lines[@]}-1]}