Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash get last line from a variable

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.

like image 769
Matt Backslash Avatar asked Sep 21 '16 11:09

Matt Backslash


People also ask

How do I get the last line in bash?

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

How do I get the last line of a shell?

To look at the last few lines of a file, use the tail command. tail works the same way as head: type tail and the filename to see the last 10 lines of that file, or type tail -number filename to see the last number lines of the file.

What is $_ in bash?

$_ (dollar underscore) is another special bash parameter and used to reference the absolute file name of the shell or bash script which is being executed as specified in the argument list. This bash parameter is also used to hold the name of mail file while checking emails.

How do I print the first and last line in Linux?

1p will print the first line and $p will print the last line. As a suggestion, take a look at info sed, not only man sed .


2 Answers

An easy way to do this is to use tail:

echo "$STRING" | tail -n1 
like image 73
redneb Avatar answered Sep 28 '22 18:09

redneb


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.

like image 42
anubhava Avatar answered Sep 28 '22 16:09

anubhava