bash 如何从bash或sh中的变量中删除最后一行?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43230731/
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
How to remove the last line from a variable in bash or sh?
提问by Alex Raj Kaliamoorthy
I have a variable that has few lines. I would like to remove the last line from the contents of the variable. I searched the internet but all the links talk about removing the last line from a file. Here is the content of my variable
我有一个有几行的变量。我想从变量的内容中删除最后一行。我在互联网上搜索过,但所有链接都在谈论从文件中删除最后一行。这是我的变量的内容
$echo $var
$select key from table_test
UNION ALL
select fob from table_test
UNION ALL
select cal from table_test
UNION ALL
select rot from table_test
UNION ALL
$
I would like to get rid of UNION ALL appearing in the last line alone.
我想去掉 UNION ALL 单独出现在最后一行。
回答by fzd
回答by Ashish K
Try this:
尝试这个:
last_line=`echo "${str##*$'\n'}"` # "${str##*$'\n'}" value gives the last line for 'str'
str=${str%$last_line} # subtract last line from 'str'
echo "${str}"
回答by Леонид Никифоренко
echo $var | head -n -1
Get all but the last line.
获取除最后一行之外的所有内容。
回答by suleiman
You could try to cut off the last line.
你可以试着剪掉最后一行。
Count=$(echo "$Var" | wc -l)
echo "$Var" | head -n $(($Count -1))
head -n $(($Count -1))
describes how many rows you want to show.
head -n $(($Count -1))
描述要显示的行数。