2012-10-31 98 views
1

我有一個配置文件,像這樣的:awk將配置文件轉換成JSON

[sectionOne] 
key1_1=value1_1 
key1_n=value1_n 


#this is a comment 
[sectionTwo] 
key2_1=value2_1 
key2_n=value2_n 

;this is a comment also 
[SectionThree] 
key3_1=value3_1 
key3_n=value3_n 
[SectionFor] 
... 

我需要翻譯成JSON這一點,使用最少的外殼工具(無Perl,Python和PHP,只是用sed,awk的可用)

所需的輸出是:

[ 
{"sectionOne": { "key1_1": "value1_1","key1_n": "value1_n"} }, 
{"sectionTwo": { "key2_1": "value2_1","key2_n": "value2_n"} }, 
{"sectionThree": { "key3_1": "value3_1","key3_n": "value3_n"}} 
.... 
] 

我試過幾種方法/小時,沒有成功

預先感謝您

+0

「我需要翻譯成JSON這一點,使用最少的外殼工具(無Perl,Python和PHP,只是用sed,awk中可用)」 - why‽如果你」已經浪費了切斷在這一小時之內,或許已經到了爲工作尋找合適工具的時候了! – Johnsyweb

+1

我看了幾分鐘,然後注意到你沒有寫任何你想要的幫助的代碼,你只是要求提供。伎倆或治療!有什麼訣竅? – ghoti

回答

1

有你的樣本輸入和期望輸出之間的一些不同之處,所以很難可以肯定的,但是這應該是接近並易於調整,如果不是100%,你想要什麼:

$ cat file 
[sectionOne] 
key1_1=value1_1 
key1_n=value1_n 


#this is a comment 
[sectionTwo] 
key2_1=value2_1 
key2_n=value2_n 

;this is a comment also 
[SectionThree] 
key3_1=value3_1 
key3_n=value3_n 
$ 
$ cat tst.awk 
BEGIN{ 
    FS="=" 
    print "[" 
} 

/^([#;]|[[:space:]]*$)/ { 
    next 
} 

gsub(/[][]/,"") { 
    printf "%s{\"%s\": { ", rs, $0 
    rs="} },\n" 
    fs="" 
    next 
} 

{ 
    printf "%s\"%s\": \"%s\"", fs, $1, $2 
    fs="," 
} 

END{ 
    print rs "]" 
} 
$ 
$ awk -f tst.awk file 
[ 
{"sectionOne": { "key1_1": "value1_1","key1_n": "value1_n"} }, 
{"sectionTwo": { "key2_1": "value2_1","key2_n": "value2_n"} }, 
{"SectionThree": { "key3_1": "value3_1","key3_n": "value3_n"} }, 
] 
1
awk 'BEGIN{ print "[" } 
    /^[#;]/{ next } # Ignore comments 
    /^\[/{ gsub("[][]", ""); printf "%s{\"%s\": { ", s ? "}},\n" : "", $0; n=0; s=1 } 
    /=/ { gsub("=", "\":\""); printf "%c\"%s\" ", n ? "," : "", $0; n=1 } 
    END{ print "}}\n]" } 
' 
0

下面是使用awk在bash的解決方案:

#!/bin/bash 

awk -F"=" 'BEGIN{in_section=0; first_field=0; printf "["} 
      { 
       last=length($1); 
       if ((substr($1,1,1) == "[") && (substr($1,last, last) == "]")) { 
        if (in_section==1) { 
         printf "} },"; 
        } 
        section=substr($1, 2, last-2); 
        printf "\n{\"%s\":", section; 
        printf " {"; 
        first_field=1; 
        in_section=1; 
       } else if (substr($1, 1, 1) == "#" || substr($1, 1, 1) == ";"){ 

       } else if (($1 != "") && ($2 != "")) { 
        if (first_field==0) { 
         printf ", "; 
        } 
        printf "\"%s\": \"%s\"", $1, $2; 
        first_field=0; 
       } 

      } 
      END{printf "} }\n]\n"}'