Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract the two first words of a string in bash

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?

like image 412
pioupiou1211 Avatar asked Oct 28 '25 09:10

pioupiou1211


1 Answers

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
like image 157
anubhava Avatar answered Oct 29 '25 23:10

anubhava