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

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

    The read command by default reads whole lines. So the solution is probably to read the whole line and then split it on whitespace with e.g. for:

    #!/bin/sh
    
    while read line; do
        for word in $line; do
            echo "word = '$word'"
        done
    done <"myfile.txt"
    

提交回复
热议问题