Shell Script: 3 Methods to Find Out Nth Word in a String

Here is my test string - This is a temporary change to complete the export. I wanted to find out nth word from the string.  I have specified the nth word in red color below
$ mystring="This is a temporary change to complete the export"

Method 1 – awk – 4th word

$ echo $mystring|awk '{ print $4}'
Temporary

Method 2 – Read – 5th word
$ read -ra sentence <<< "$mystring"; echo "${sentence[4]}"
Change

Method 3 – cut – 4th word
$ echo $mystring | cut -d" " -f4

temporary

No comments:

Post a Comment