Yokai Seishinkage Yokai Seishinkage - 5 months ago 7
Bash Question

Read a single word from a string and set as a variable value in bash

I have a need for a simple function to do the following:

#!/bin/bash

select_word() {

echo "Enter a string."
read STRING

## User enters "This is a string."

## Here will be the command to set each word to the below variables.

WORD_1=
WORD_2=
WORD_3=
WORD_4=

echo -e "Word 1 is: $WORD_1.\n Word 2 is: $WORD_2.\n"
echo -e "Word 3 is: $WORD_3.\n Word 4 is: $WORD_4.\n"
}


I am wanting to avoid using external tools such as sed or awk. Looking for bash builtin functions to use in order to pull each word from the string and set that word as a variable. I will later use "wc" to count the number of characters in each word. I already know how to do that, I just need to know the bash method to pulling a word from user input strings.

If this question is a duplicate, I apologize as I could not find this specific question.

Answer

You can convert the space delimited $STRING into an array, and then reference each array element in $WORD_n variables:

   WORDS=($STRING)

   WORD_1=${WORDS[0]}
   WORD_2=${WORDS[1]}