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.
${str##*$'\n'} will remove the longest match till \n from start of the string thus leaving only the last line in input.
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.
$_ (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.
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 .
An easy way to do this is to use tail
:
echo "$STRING" | tail -n1
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.
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