Bash将数组展平为键值对

时间:2017-07-14 11:17:00

标签: arrays linux bash shell

我有一个下面提到的数组。

阵列

wf.example.input1=/path/to/file1 
wf.example.input2=/path/to/file2 
wf.example.input3=["/path/to/file3","/path/to/file4"]

declare -p Array给我低于输出。

([0]="wf.example.input1=/path/to/file1" [1]="wf.example.input2=/path/to/file2" [2]="wf.example.input3=[\"/path/to/file3\",\"/path/to/file4\"]")

我需要展平这个数组ib bash脚本并给我输出如下。

输出

name:"wf.example.input1", value:"/path/to/file1"
name:"wf.example.input2", value:"/path/to/file2"
name:"wf.example.input3", value:"/path/to/file3"
name:"wf.example.input3", value:"/path/to/file4"

1 个答案:

答案 0 :(得分:4)

使用printf管道传输到awk进行格式化:

declare -a arr='([0]="wf.example.input1=/path/to/file1"
[1]="wf.example.input2=/path/to/file2"
[2]="wf.example.input3=[\"/path/to/file3\",\"/path/to/file4\"]")'

printf "%s\n" "${arr[@]}" |
awk -F= '{
   n=split($2, a, /,/)
   for (i=1; i<=n; i++) {
      gsub(/^[^"]*"|"[^"]*$/, "", a[i])
      printf "name:\"%s\", value:\"%s\"\n", $1, a[i]
   }
}'

<强>输出:

name:"wf.example.input1", value:"/path/to/file1"
name:"wf.example.input2", value:"/path/to/file2"
name:"wf.example.input3", value:"/path/to/file3"
name:"wf.example.input3", value:"/path/to/file4"