Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nth word in a string variable

Tags:

bash

In Bash, I want to get the Nth word of a string hold by a variable.

For instance:

STRING="one two three four" N=3 

Result:

"three" 

What Bash command/script could do this?

like image 402
Nicolas Raoul Avatar asked Jun 09 '10 12:06

Nicolas Raoul


People also ask

How do I find the second word in a string?

ToString(); var secondWord = tbt. Substring(indexnumber, tbt. IndexOf(" ")); var indexword2 = tbt. IndexOf(" ", indexnumber); var indexnumber2 = indexword2 + 1; string myString2 = indexnumber2.

How do I extract the first last nth word from a text string in Excel?

(1) Select Text from the Formula type drop-down list; (2) Click to highlight Extract the nth word in cell in the Choose a formula list box; (3) In the Cell box, specify the cell that you will extract word from; (4) In The Nth box, specify the number.


2 Answers

echo $STRING | cut -d " " -f $N 
like image 143
Amardeep AC9MF Avatar answered Sep 30 '22 09:09

Amardeep AC9MF


An alternative

N=3 STRING="one two three four"  arr=($STRING) echo ${arr[N-1]} 
like image 38
aioobe Avatar answered Sep 30 '22 07:09

aioobe