【问题标题】:how to parse a string word by word in a shell script?如何在shell脚本中逐字解析字符串?
【发布时间】:2013-01-08 15:09:54
【问题描述】:

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

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"

提前感谢您的帮助!!!

【问题讨论】:

  • 你可以使用这个 [link][1] 来找到你的答案 :) [1]: stackoverflow.com/questions/1469849/…
  • 第4行第10个字应该是“我”吗?您确定“单词”何时结束的标准是什么?
  • 单词列表与线路的音素列表之间用制表符隔开

标签: string shell


【解决方案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

【讨论】:

  • 非常感谢!一个制表符将单词与该行的其余部分分开。
  • 我想只取电话列表之前的单词。实际上我想摆脱每行中的电话列表。
猜你喜欢
  • 2012-02-26
  • 1970-01-01
  • 1970-01-01
  • 2012-12-21
  • 1970-01-01
  • 2018-11-08
  • 2018-12-05
  • 2015-09-04
  • 2021-02-24
相关资源
最近更新 更多