Bash: How to Get the Nth Word in a String


Often you may want to use Bash to get the Nth word in a string.

You can use the following syntax to do so:

echo $my_string | cut -d " " -f3

This particular example will return the third word in the string variable named my_string.

This syntax uses the cut command to extract a specific field from a line, using the -d parameter to specify the delimiter and the -f parameter to specify the field to extract.

The following example shows how to use this syntax in practice.

Example: How to Get the Nth Word in a String Using Bash

We can use the following syntax to create a string variable named my_string and then get only the third word from the string:

my_string="I hope you have a great day"
echo $my_string | cut -d " " -f3

The following screenshot shows how to use this syntax in practice:

Bash get nth word from string

This returns the word you, which is indeed the third word in the string variable.

We can replace -f3 with a different number to get a different word instead.

For example, we can use -f6 to get the sixth word in the string variable instead:

my_string="I hope you have a great day"
echo $my_string | cut -d " " -f6

The following screenshot shows how to use this syntax in practice:

This returns the word great, which is indeed the sixth word in the string variable.

Note: If you specify a number greater than the number of words in the string, then this syntax will simply return a blank.

Related Tutorials

The following tutorials explain how to perform other common tasks in Bash:

Bash: How to Count Number of Words in String
Bash: How to Count Number of Characters in String
Bash: How to Count Number of Unique Lines in File

Leave a Reply