44

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 a
multiple line
variable 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.

gniourf_gniourf
  • 44,650
  • 9
  • 93
  • 104
Matt Backslash
  • 764
  • 1
  • 8
  • 20

3 Answers3

79

An easy way to do this is to use tail:

echo "$STRING" | tail -n1
redneb
  • 21,794
  • 6
  • 42
  • 54
35

Using bash string manipulations:

$> str="This is a
multiple line
variable 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.

anubhava
  • 761,203
  • 64
  • 569
  • 643
2

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]}.

chepner
  • 497,756
  • 71
  • 530
  • 681
  • 1
    A small note may be stating need `bash 4.x`? – Inian Sep 21 '16 at 11:44
  • IMO, 3.x should just be treated as a POSIX-compatible shell on par with `dash`, but with better features for interactive use. I consider the nearly 6-year-old `bash` 4.2 release a reasonable baseline assumption now. – chepner Sep 21 '16 at 11:54
  • Still using `GNU bash, version 4.1.2` btw :), in which it is not supported. :( Thought would be good point to add for a proper reference. – Inian Sep 21 '16 at 11:57
  • I also consider knowing what version of `bash` you are using to be part of your due diligence in asking a question. I am no longer presenting a laundry list of options to cater to 3 or more different versions of `bash` in every answer. I'm taking Python as my model, where the assumption is that you are using Python 3.3+ unless otherwise stated, and Python 2 pretty much means Python 2.7. – chepner Sep 21 '16 at 12:06
  • Cheers! no disrespect meant! – Inian Sep 21 '16 at 12:07
  • 1
    None taken! This is a little rant that's been building in me for some time, and there's no good place for it :) I'd love to get some consensus and put a note in the `bash` tag info about what features we can reasonably assume, but no one asking questions reads that page anyway. – chepner Sep 21 '16 at 12:22