user1835630
user1835630

Reputation: 261

how to parse a string word by word in a shell script?

I have a file containing strings like (the number of words in any string is random):

coge las hojas y las quemas todas en el fuego   k Wo x e l a s Wo x a s i l a s k We m a s t Wo D a s e n e l f w We G o 
la liga de paz se reunió para tratar el tema    l a l Wi G a d e p Wa T s e rr e w n j Wo p a r a t r a t Wa r e l t We m a
el bebé se mete el pie dentro de la boca    e l b e B We s e m We t e e l p j We d We n t r o d e l a b Wo k a
hoy en día el pollo es un plato común   Wo j e n d Wi a e l p Wo L o We s Wu n p l Wa t o k o m Wu n

I want to separate the string in words. For example, I would like to have from the first sentence 10 variables v1,v2,..v10 so that:

v1="coge"
v2="las"
...
v10="fuego"

Thank you in advance for your help!!!

Upvotes: 1

Views: 4061

Answers (1)

glenn jackman
glenn jackman

Reputation: 246827

Assuming that 3 or more spaces separates the words from the rest of the line:

while IFS= read -r line; do
    read -ra words <<< ${line%%   *}

    # do whatever you need with the words array here, for example
    for (( i=0; i<${#words[@]}; i++ )); do
        printf "%d - %s\n" $i "${words[i]}"
    done
done < filename

To use a tab character:

while IFS=$'\t' read -r words phones; do
    read -ra words_ary <<< $words

    # do whatever you need with the words array here, for example
    for (( i=0; i<${#words_ary[@]}; i++ )); do
        printf "%d - %s\n" $i "${words_ary[i]}"
    done
done < filename

Upvotes: 1

Related Questions