How to split one string into multiple strings separated by at least one space in bash shell?

前端 未结 8 1318
日久生厌
日久生厌 2020-11-27 09:17

I have a string containing many words with at least one space between each two. How can I split the string into individual words so I can loop through them?

The stri

8条回答
  •  情话喂你
    2020-11-27 09:55

    Just use the shells "set" built-in. For example,

    set $text
    

    After that, individual words in $text will be in $1, $2, $3, etc. For robustness, one usually does

    set -- junk $text
    shift
    

    to handle the case where $text is empty or start with a dash. For example:

    text="This is          a              test"
    set -- junk $text
    shift
    for word; do
      echo "[$word]"
    done
    

    This prints

    [This]
    [is]
    [a]
    [test]
    

提交回复
热议问题