If I have a variable with multiple lines (text) in it, how can I get the last line out of it?

I already figured out how to get the first line:

STRING="This is amultiple linevariable test"FIRST_LINE=(${STRING[@]})echo "$FIRST_LINE"# output:"This is a"

Probably there should be an operator for the last line. Or at least I assume that because with @ the first line comes out.

3

Best Answer


An easy way to do this is to use tail:

echo "$STRING" | tail -n1

Using bash string manipulations:

$> str="This is amultiple linevariable test"$> echo "${str##*$'\n'}"variable test

${str##*$'\n'} will remove the longest match till \n from start of the string thus leaving only the last line in input.

If you want an array with one element per line from STRING, use

readarray -t lines <<< "$STRING"

Then, the first line would be ${lines[0]}, and the last line would be ${lines[-1]}. In older versions of bash, negative indices aren't allowed and you'll have to compute the last index manually: ${lines[${#lines[@]}-1]}.