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

前端 未结 7 1868
眼角桃花
眼角桃花 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 13:13

    In bash, just use space as delimiter (read -d ' '). This method requires some preprocessing to translate newlines into spaces (using tr) and to merge several spaces into a single one (using sed):

    {
     tr '\n' ' ' | sed 's/  */ /g' | while read -d ' ' WORD
     do
      echo -n "<${WORD}> "
     done
     echo
    } << EOF
    Here you have some words, including * wildcards
    that don't get expanded,
    multiple   spaces   between   words,
        and lines with spaces at the begining.
    EOF
    

    The main advantage of this method is that you don't need to worry about the array syntax and just work as with a for loop, but without wildcard expansion.

提交回复
热议问题