1

我有一个像这样的配置文件:

[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]
...

我需要使用最少的 shell 工具将它翻译成 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"}}
....
]

我尝试了几种方法/小时,没有成功

先感谢您

4

3 回答 3

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"} },
]
于 2012-10-31T19:14:22.793 回答
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]" }
' 
于 2012-10-31T19:14:34.897 回答
0

这是使用 bash 的解决方案awk

#!/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"}'
于 2012-10-31T19:21:53.060 回答