5

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.

Alex Raj Kaliamoorthy
  • 2,035
  • 3
  • 29
  • 46

5 Answers5

14

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

fzd
  • 765
  • 1
  • 6
  • 19
2
echo $var | head -n -1

Get all but the last line.

Ondrej K.
  • 8,841
  • 11
  • 24
  • 39
1

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.

Mario
  • 679
  • 6
  • 10
1

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}"
Ashish K
  • 905
  • 10
  • 27
1

Bash way:

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

This prints $var with all characters incl. and after the last LF removed.

svobodb
  • 56
  • 5