Nth word in a string variable

Bash

Bash Problem Overview


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?

Bash Solutions


Solution 1 - Bash

echo $STRING | cut -d " " -f $N

Solution 2 - Bash

An alternative

N=3
STRING="one two three four"

arr=($STRING)
echo ${arr[N-1]}

Solution 3 - Bash

Using awk

echo $STRING | awk -v N=$N '{print $N}'

Test

% N=3
% STRING="one two three four"
% echo $STRING | awk -v N=$N '{print $N}'
three

Solution 4 - Bash

A file containing some statements:

cat test.txt

Result:

This is the 1st Statement
This is the 2nd Statement
This is the 3rd Statement
This is the 4th Statement
This is the 5th Statement

So, to print the 4th word of this statement type:

awk '{print $4}' test.txt

Output:

1st
2nd
3rd
4th
5th

Solution 5 - Bash

No expensive forks, no pipes, no bashisms:

$ set -- $STRING
$ eval echo \${$N}
three

Or, if you want to avoid eval,

$ set -- $STRING
$ shift $((N-1))
$ echo $1
three

But beware of globbing (use set -f to turn off filename globbing).

Solution 6 - Bash

STRING=(one two three four)
echo "${STRING[n]}"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNicolas RaoulView Question on Stackoverflow
Solution 1 - BashAmardeep AC9MFView Answer on Stackoverflow
Solution 2 - BashaioobeView Answer on Stackoverflow
Solution 3 - BashjkshahView Answer on Stackoverflow
Solution 4 - BashAkhiljith P BView Answer on Stackoverflow
Solution 5 - BashJensView Answer on Stackoverflow
Solution 6 - BashmnrlView Answer on Stackoverflow