2017-07-14 67 views
1

我有一個如下所示的數組。Bash將數組展開爲鍵值對

陣列

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" 
+0

@anubhava這個陣列會被科曼g作爲我的一個輸入。我不是創建這個數組的人。我需要生成我的問題中提到的所需輸出。 – Shashank

+0

無論你得到什麼輸入,你都可以使用'declare -p array'來檢查它 – anubhava

回答

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" 
+1

這正是我所要求的。 +1 – Shashank