从命令输出中提取值到JSON

时间:2017-04-11 04:29:20

标签: bash shell awk ibm-cloud

我从云代工厂命令中提取值。它必须通过shell完成。以下是文件的外观:

User-Provided:
end: 123.12.12.12
text_pass: 980
KEY: 000

Running Environment Variable Groups:
BLUEMIX_REGION: ibm:yp:us-north

Staging Environment Variable Groups:
BLUEMIX_REGION: ibm:yp:us-south

我想提取从end到KEY的所有内容,请注意用户提供的内容始终是开头,但结尾可以是任何值。但总会有新的界限。

如何在“User-provided to new line”之间提取并输入我稍后将用于解析的JSON文件?

到目前为止,我能够做到这一点:

  

cf env space | awk -F 'end:' '{print $2}'

这给了我结束的价值而不是整个对象。

预期产出:

{
"end": "123.12.12.12"
"text_pass": "980"
"KEY": "000"
}

2 个答案:

答案 0 :(得分:1)

cf env space | awk '/User-Provided/{a = 1; next}/^$/{a = 0} a'

end: 123.12.12.12
text_pass: 980
KEY: 000

遇到模式User-Provided时设置变量a,当遇到空行时,取消设置此变量a。现在,仅在设置a的情况下打印出行。

编辑回答:

cf env space |  awk -F" *: *" '/User-Provided/{a=1;print"{";next}/^$/{a=0} END{print "\n}"} a{if(c)printf(","); printf("%s", "\n\""$1"\" : \""$NF"\""); c=1}'

这将给出输出:

{

"end" : "123.12.12.12",
"text_pass" : "980",
"KEY" : "000"
}

最新编辑:

cf env space | awk '/User-Provided/{a=1;print"{";next}/^$/{a=0} END{print "\n}"} a{if(c)printf(","); sub(/:$/,"",$1); printf("%s", "\n\""$1"\" : \""$NF"\""); c=1}'

答案 1 :(得分:1)

在awk中:

$ awk '/^end:/,/^KEY:/' file
end: 123.12.12.12
text_pass: 980
KEY: 000

/.../,/.../用于命名打印的开始和结束标记。

但是,输出要求使程序有点复杂化:

$ awk '
BEGIN { FS=": *";OFS=":" }           # set appropriate delimiters
/^end:/ { print "{";f=1 }            # print at start marker and raise flag
f { print "\"" $1"\"","\"" $2"\"" }  # when flag up, print
/^KEY:/ { print "}";f="" }           # at end-marker, print end marker and flag down
' file
{
"end":"123.12.12.12"
"text_pass":"980"
"KEY":"000"
}

如果您想使用空行作为结束标记,请使用/^$/ && f代替/^KEY:/