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

前端 未结 8 1207
日久生厌
日久生厌 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 10:02

    For checking spaces just with bash:

    [[ "$str" = "${str% *}" ]] && echo "no spaces" || echo "has spaces"
    
    0 讨论(0)
  • 2020-11-27 10:04

    I like the conversion to an array, to be able to access individual elements:

    sentence="this is a story"
    stringarray=($sentence)
    

    now you can access individual elements directly (it starts with 0):

    echo ${stringarray[0]}
    

    or convert back to string in order to loop:

    for i in "${stringarray[@]}"
    do
      :
      # do whatever on $i
    done
    

    Of course looping through the string directly was answered before, but that answer had the the disadvantage to not keep track of the individual elements for later use:

    for i in $sentence
    do
      :
      # do whatever on $i
    done
    

    See also Bash Array Reference.

    0 讨论(0)
提交回复
热议问题