I have a string with a sentence within like
a="hello my dear friend". I want to retrieve the first two words (here it should be "hello my"), knowing that the number of words can vary. I tried ${a%% *} but it only gives me the first one.
In the same kind, I need to extract the whole sentence without the two first words. How can I do that?
You can use BASH arrays for this:
# construct an array delimited by whitespace
a="hello my dear friend"
arr=($a)
# first two words
echo "${arr[@]:0:2}"
hello my
# anything after first 2 words
echo "${arr[@]:2}"
dear friend
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