Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 816
Alex Raj Kaliamoorthy Avatar asked Apr 05 '17 12:04

Alex Raj Kaliamoorthy


People also ask

How to remove the last character from a variable in Bash?

Therefore, we can pass -1 as the length to remove the last character from the variable: Also, Bash allows us to omit the offset if it’s ‘ 0 ‘: $ {var::-1} However, we should keep in mind that Bash’s substring expansion with the negative length won’t work for empty strings:

How to remove the last line from a file in Linux?

This approach is the way to go for large files! To remove the last line from a file without reading the whole file or rewriting anything, you can use To remove the last line and also print it on stdout ("pop" it), you can combine that command with tee: These commands can efficiently process a very large file.

How to remove the last characters from a string in Python?

Let’s have a look at different ways of removing the last characters from a string. To remove the last characters from a string, type the variable name followed by a % symbol and a number of ? symbols equal to the number of characters to be removed. variable="verylongstring" echo $ {variable%??????}

How do I remove the last n characters from a line?

for removing the last n characters from a line that makes no use of sed OR awk: > echo lkj | rev | cut -c (n+1)- | rev so for example you can delete the last character one character using this: > echo lkj | rev | cut -c 2- | rev > lk


2 Answers

sed can do it the same way it would do it from a file :

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

EDIT : $ represents the last line of the file, and d deletes it. See here for details

like image 189
fzd Avatar answered Oct 14 '22 04:10

fzd


echo $var | head -n -1

Get all but the last line.

like image 2
Леонид Никифоренко Avatar answered Oct 14 '22 04:10

Леонид Никифоренко