我有一个下面提到的数组。
数组
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"
最佳答案
使用 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"
关于arrays - Bash 将数组展平为键值对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45101660/