Split string into an array in Bash

后端 未结 22 2269
故里飘歌
故里飘歌 2020-11-22 04:24

In a Bash script I would like to split a line into pieces and store them in an array.

The line:

Paris, France, Europe

I would like

相关标签:
22条回答
  • 2020-11-22 05:03

    Another way to do it without modifying IFS:

    read -r -a myarray <<< "${string//, /$IFS}"
    

    Rather than changing IFS to match our desired delimiter, we can replace all occurrences of our desired delimiter ", " with contents of $IFS via "${string//, /$IFS}".

    Maybe this will be slow for very large strings though?

    This is based on Dennis Williamson's answer.

    0 讨论(0)
  • Use this:

    countries='Paris, France, Europe'
    OIFS="$IFS"
    IFS=', ' array=($countries)
    IFS="$OIFS"
    
    #${array[1]} == Paris
    #${array[2]} == France
    #${array[3]} == Europe
    
    0 讨论(0)
  • 2020-11-22 05:07

    if you use macOS and can't use readarray, you can simply do this-

    MY_STRING="string1 string2 string3"
    array=($MY_STRING)
    

    To iterate over the elements:

    for element in "${array[@]}"
    do
        echo $element
    done
    
    0 讨论(0)
  • 2020-11-22 05:08

    Sometimes it happened to me that the method described in the accepted answer didn't work, especially if the separator is a carriage return.
    In those cases I solved in this way:

    string='first line
    second line
    third line'
    
    oldIFS="$IFS"
    IFS='
    '
    IFS=${IFS:0:1} # this is useful to format your code with tabs
    lines=( $string )
    IFS="$oldIFS"
    
    for line in "${lines[@]}"
        do
            echo "--> $line"
    done
    
    0 讨论(0)
提交回复
热议问题