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

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

How to remove the last line from a variable in bash or sh?

bashtext-processing

提问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

sedcan do it the same way it would do it from a file :

sed可以像从文件中那样做:

> echo "$var" | sed '$d'

EDIT : $represents the last line of the file, and ddeletes it. See herefor details

EDIT :$代表文件的最后一行,并d删除它。见这里了解详细信息

回答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))描述要显示的行数。