2017-07-14 2 views
1

Ich habe ein Array unten erwähnt.Bash flattern ein Array zu Schlüssel-Wert-Paar

Array

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

declare -p Array gibt mir unten ausgegeben.

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

Ich muss dieses Array Ib Bash Skript glätten und geben Sie mir Ausgabe wie unten.

Ausgabe

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 Dieses Array Comin wird g als eine Eingabe für mich. Ich bin nicht derjenige, der dieses Array erstellt. Und ich muss die gewünschte Ausgabe erzeugen, wie in meiner Frage erwähnt. – Shashank

+0

Welche Eingabe Sie auch erhalten, Sie können sie mit 'declare -p array' untersuchen. – anubhava

Antwort

4

Mit printf zu awk geleitet werden Formatierung:

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] 
    } 
}' 

Ausgang:

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

Dies ist genau das, was ich benötigt habe. +1 – Shashank

Verwandte Themen