Bash从JSON输出中提取字符串并将其保存到Array中

时间:2016-12-30 17:08:06

标签: bash loops awk sed grep

我正在尝试从一个字符串中提取几个子字符串,我想将这些子字符串保存在一个数组中,所以我想使用一个循环,但我真的很喜欢bash脚本。

原始字符串类似于:

Array[0]=Place%20Henri%20Gadeau%20de%20Kerville%2C%20Centre%20Ville%20Rive%20Gauche;
Array[1]=Rue%20Charles%20de%20Gaulle%2C%20Saint-Arnoult-en-Yvelines;
Array[2]=Rue%20des%20Remparts%2C%20Saint-Arnoult-en-Yvelines;
Array[3]=Rue%20Marie%20Duboccage%20(Saint-Sever)%2C%20Rouen;
Array[4]=Rue%20Octave%20Crutel%2C%20Rouen;
...

所需的输出是一个数组,其名称为url模式,来自“name”标签,如:

grep

为了将Array的值保存在另一个文件中然后使用它们。 我试过grep -o '^\"name\":.*\},$' $var

src/main/java

但我无法取得好成绩。

1 个答案:

答案 0 :(得分:1)

bash简单循环中,使用JSON解析工具jq和流程替换

#!/bin/bash

jsonArray=()
while IFS= read -r line
do
    jsonString="${line// /%20}"           # Replace blank-spaces with '%20'
    jsonString="${jsonString//,/%2C}"     # Replace ',' with empty '%2C'
    jsonString+=";"                       # Append a ';' at end of string
    jsonArray+=("$jsonString")            # Add it to the array
done< <(jq -r '.groups[].favourites[].name' newfile)

printf "%s\n" "${jsonArray[@]}"           # "${jsonArray[0]}","${jsonArray[1]}"...

在我的例子中,我在文件中使用了字符串,为你的情况替换了行

done< <(jq -r '.groups[].favourites[].name' newfile)

使用实际命令生成JSON输出为

done < <( json-cmd | jq -r '.groups[].favourites[].name')

运行脚本

$ bash script.sh
Place%20Henri%20Gadeau%20de%20Kerville%2C%20Centre%20Ville%20Rive%20Gauche;
Rue%20Charles%20de%20Gaulle%2C%20Saint-Arnoult-en-Yvelines;
Rue%20des%20Remparts%2C%20Saint-Arnoult-en-Yvelines;
Rue%20Marie%20Duboccage%20(Saint-Sever)%2C%20Rouen;
Rue%20Octave%20Crutel%2C%20Rouen;