arrays - Bash 将数组展平为键值对

标签 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"

最佳答案

使用 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/

相关文章:

php - stdClass 对象和数组键值

bash - 有没有办法在退出时执行命令(无论脚本如何退出)?

linux - 有人可以建议支持复杂数据的高性能共享内存 API 吗?

linux - 我可以在 Linux 中混合文本和二进制文件吗?

linux - 在单个文件夹中运行 3 个脚本

bash - 通过搜索从字符串中提取 2 个字段

bash - shell脚本内存不足

arrays - Kotlin - Val 无法重新分配,但可以通过从索引访问来重新分配?

arrays - 如何使用 spring JdbcTemplate 更新 postgresql 数组列?

java - 为数组实现撤销和重做