如何在shell脚本中逐字解析字符串?

时间:2013-01-24 18:45:50

标签: string shell

我有一个包含字符串的文件(任何字符串中的单词数是随机的):

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

我想用单词分隔字符串。例如,我想从第一句话中得到10个变量v1,v2,... v10,以便:

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

提前感谢您的帮助!!!

1 个答案:

答案 0 :(得分:1)

假设3个或更多空格将单词与行的其余部分分开:

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

使用制表符:

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