tags:

views:

72

answers:

2

In bash, I want to get the Nth word of a string.

For instance:

  • STRING="one two three four"
  • N=3
  • Result: "three"

What bash command/script could do this?
Thank you!

+4  A: 
echo $STRING | cut -d \  -f $N
Amardeep
Please note that there is two spaces after the \ symbol.
Joe
Alternatively you can put the space in quotes - IMHO this is more readable. i.e. echo $STRING | cut -d " " -f $N
Dave Kirby
Works great, thanks :-D
Nicolas Raoul
+2  A: 

An alternative

N=3
STRING="one two three four"

arr=($STRING)
echo ${arr[N-1]}
aioobe
The `echo` isn't necessary and I don't know why you're replacing a space with a space. This works just fine: `arr=($STRING)`
Dennis Williamson
I just modified an example of the web.. (stupid). Thanks for your comment. Updated.
aioobe