如何从 bash 或 sh 中的变量中删除最后一行?

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

我有一个只有几行的变量。我想从变量的内容中删除最后一行。我搜索了互联网,但所有链接都在谈论从文件中删除最后一行。 这是我的变量的内容

$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
$

我想摆脱单独出现在最后一行的 UNION ALL。

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

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

EDIT : $ 表示文件的最后一行,d 将其删除。 详情见here

你可以试着把最后一行删掉。

Count=$(echo "$Var" | wc -l)
echo "$Var" | head -n $(($Count -1))

head -n $(($Count -1)) 说明您要显示多少行。

试试这个:

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}"
echo $var | head -n -1

获取除最后一行以外的所有内容。

Bash方式:

echo "${var%$'\n'*}"

这将打印 $var 所有字符,包括。并在删除最后一个 LF 之后。