How can I read words (instead of lines) from a file?

前端 未结 7 1865
眼角桃花
眼角桃花 2020-12-16 12:37

I\'ve read this question about how to read n characters from a text file using bash. I would like to know how to read a word at a time from a file that looks like:



        
7条回答
  •  星月不相逢
    2020-12-16 12:54

    In the context given, where the number of words is known:

    while read -r word1 word2 _; do
      echo "Read a line with word1 of $word1 and word2 of $word2"
    done
    

    If you want to read each line into an array, read -a will put the first word into element 0 of your array, the second into element 1, etc:

    while read -r -a words; do
      echo "First word is ${words[0]}; second word is ${words[1]}"
      declare -p words # print the whole array
    done
    

提交回复
热议问题