使用另一个字符串在变量中拆分值并存储在数组中(Bash)

时间:2018-11-29 12:41:30

标签: linux bash shell scripting

我有一个变量 diagnosisCodes ,其值如下所示:

echo $diagnosisCodes
{"code":"some code1","codeSet":"some set1","description":"some description1"} {"code":"some code2","codeSet":"some set2","description":"some description2"} {"code":"some code3","codeSet":"some set3","description":"some description3"}

我想使用定界符"} {"分割它们,以便获得3个不同的值,然后将它们存储在数组中(以bash表示)。

我使用以下命令找到了解决方案(由Incrivel Monstro Verde在注释中建议):

IFS='|' read -r -a array <<< $(echo $string | sed 's/{"code/|"code/g;s/\"}/"/g')

但是,如果我的字符串具有“ codeSet”属性,而该属性在“ code”属性之前,则此解决方案将失败。

2 个答案:

答案 0 :(得分:0)

您可以使用以下内容:

#!/bin/bash

string='{"code":"some code1","codeSet":"some set1","description":"some description1"} {"code":"some code2","codeSet":"some set2","description":"some description2"} {"code":"some code3","codeSet":"some set3","description":"some descripti

IFS='{' read -r -a array <<< $(echo $string | sed 's/}//g')

echo "${array[1]}"
echo "${array[2]}"
echo "${array[3]}"

答案 1 :(得分:0)

尝试一下

#!/bin/bash

string='{"code":"some code1","codeSet":"some set1","description":"some description1"} {"code":"some code2","codeSet":"some set2","description":"some description2"} {"code":"some code3","codeSet":"some set3","description":"some description3"}'
var="${string//\} {/$'|'}" #replace '} {' with '|' , works for one space only between '} {'
IFS='|' read -r -a array <<< $(echo $var | sed 's/{//g;s/}//g')
for i in "${array[@]}"
  do
    echo $i
  done