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.
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:
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.
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%??????}
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
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
echo $var | head -n -1
Get all but the last line.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With