When parsing and read from a simple string, Here Strings is a good choice to utilize, for example:


TEXT='a b c d'
read a b rest <<< "$TEXT"
echo $b - $rest

Results:


b - c d

You can also use -a for reading into an array, for example:


TEXT='a b c d'
read -a ARRAY <<< "$TEXT"
echo ${ARRAY[1]} - ${ARRAY[@]:2}

My preference is to specify variables instead of reading into an array above, I like refer to with specific variables. Note that you don’t need to read everything to their own variables, when there is more the rest would be stuffed into the last variable.

Sometimes, the string isn’t delimited by spaces, for example, a simple CSV-like string:


TEXT='a,b,c,d'
IFS=, read a b rest <<< "$TEXT"
echo $b - $rest

Gives:


b - c,d

By changing IFS, the Internal Field Separator, read can be fed with a data delimited by the desired delimiter.

To be more advanced, you can read data like record/field, for example:


TEXT='a,b,c,d
1,2,3,4'

while IFS=, read a b rest; do
echo $b - $rest
done <<< "$TEXT"

Produces:


b - c,d
2 - 3,4

In the example above, the data is fed into a while loop, where read get the data when each line comes in, just like previous examples. You can of course echo in the data to the loop, but that will create a subshell, using Here Strings is more efficient on that account since it doesn’t need to create one.