将bash字符串转换为数组


3

我有一个名为script.js的脚本(在Node.js中),它输出以下字符串:

(1, 2, 3)

我想通过以下方式循环读取它:

INDICES=$(node script.js)
for i in "{INDICES[@]}"
do
    echo $i
done

而不是打印

1
2
3

我明白了

(1, 2, 3)

由于脚本输出被读取为字符串。

我如何使它成为一个数组?


我建议你在stackoverflow问这个...
djsmiley2k

@ djsmiley2k为什么? Bash问题在这里是主题。
DavidPostill

@DavidPostill他们是?好。 :)
djsmiley2k

Answers:


2
#!/bin/bash

inputstr="(1, 2, 3)"

newstr=$(echo $inputstr | sed 's/[()]//g' ) # remove ( and )

IFS=', ' read -r -a myarray <<< "$newstr" # delimiter is ,

for index in "${!myarray[@]}"
do
    # echo "$index ${myarray[index]}"  #  shows index and value
      echo        "${myarray[index]}"  #  shows           value
done

给出这个输出

./string_to_array.sh
1
2
3

2

Scott的解决方案非常好,但它使用外部流程。这是一个仅使用bash内置的方法:

#!/bin/bash

inputstr="(one, two, three)"
tempvar=$(echo $inputstr)
array=(${tempvar//[\(\),]/})

for value in "${array[@]}"; do
  echo "${value}"
done
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.