Reading a delimited string into an array in Bash

前端 未结 5 1301
旧时难觅i
旧时难觅i 2020-11-29 15:17

I have a variable which contains a space-delimited string:

line=\"1 1.50 string\"

I want to split that string with space as a delimiter and

相关标签:
5条回答
  • 2020-11-29 15:37

    In order to convert a string into an array, please use

    arr=($line)
    

    or

    read -a arr <<< $line
    

    It is crucial not to use quotes since this does the trick.

    0 讨论(0)
  • 2020-11-29 15:40

    In: arr=( $line ). The "split" comes associated with "glob".
    Wildcards (*,? and []) will be expanded to matching filenames.

    The correct solution is only slightly more complex:

    IFS=' ' read -a arr <<< "$line"
    

    No globbing problem; the split character is set in $IFS, variables quoted.

    0 讨论(0)
  • 2020-11-29 15:40

    If you need parameter expansion, then try:

    eval "arr=($line)"
    

    For example, take the following code.

    line='a b "c d" "*" *'
    eval "arr=($line)"
    for s in "${arr[@]}"; do 
        echo "$s"
    done
    

    If the current directory contained the files a.txt, b.txt and c.txt, then executing the code would produce the following output.

    a
    b
    c d
    *
    a.txt
    b.txt
    c.txt
    
    0 讨论(0)
  • 2020-11-29 15:42

    Try this:

    arr=(`echo ${line}`);
    
    0 讨论(0)
  • 2020-11-29 15:49
    line="1 1.50 string"
    
    arr=$( $line | tr " " "\n")
    
    for x in $arr
    do
    echo "> [$x]"
    done
    
    0 讨论(0)
提交回复
热议问题