1

I am still new to awk but I have an awk command that does 90% of what I want to do. The line I am splitting looks like this.

Key1^C{"s":"VALUE"}^BKEY2^C{"s":"VALUE"}^BKEY3^C{"s":"VALUE"}

I am splitting it with this awk command

awk -F'\02' '{for(x=1; x<=NF; x++) {nf=split($x,f,"\03"); print f[1], "--", f[2], ","}}' inputfile > outputfile.txt

It comes out looking like this

Key1 -- Value,
Key2 -- Value,
Key3 -- Value,

I was hoping someone could help point me in the direction of how to instead if it is possible to have it look something like this

Key1 -- Value, Key2 -- Value, Key3 -- Value
4

3 回答 3

2

试试这个:(根据你的命令):

awk -F'\02' '{for(x=1; x<=NF; x++) {nf=split($x,f,"\03"); printf "%s",f[1]" -- " f[2] (x==NF?"": ",")}print ""}' inputfile > outputfile.txt
于 2013-08-09T13:11:07.833 回答
0
awk -F'[\02\03"]' '{sep="";for(i=1;i<NF;i+=6){printf "%s%s -- %s",sep,$i,$(i+4);sep=", "}}END{print ""}' some.file

或者,更具可读性:

awk -F'[\02\03"]' '
    {
        sep = ""
        for (i=1; i<NF; i+=6) {
            printf "%s%s -- %s", sep, $i, $(i+4)
            sep = ", "
        }
    }
    END {print ""}
' some.file

这使用 ^B 和 ^C 和 " 作为字段分隔符。我假设 ^C 之后的 JSON 片段总是同时引用键和值。

于 2013-08-09T13:56:56.353 回答
0

尝试这个:

awk -F'\02' '{for(x=1; x<=NF; x++) {nf=split($x,f,"\03"); tmpvar=tmpvar" "f[1], "--", f[2], ","}}END{sub(/,$/,"",tmpvar); print tmpvar}' inputfile > outputfile.txt
于 2013-08-09T13:10:35.033 回答