我将以下格式的数据存储在文件中。
ABC:9804
{
"count" : 492,
"_shards" : {
"total" : 19,
"successful" : 19,
"failed" : 0
}
}
Bye
ABC:95023
{
"count" : 865,
"_shards" : {
"total" : 19,
"successful" : 19,
"failed" : 0
}
}
Bye
ABCC:128
{
"count" : 479,
"_shards" : {
"total" : 19,
"successful" : 19,
"failed" : 0
}
}
Bye
我正在尝试输出
ABC:9804 , 492
ABC:95023 , 865
ABCC:128 , 479
我尝试使用awk获得第1行和第3行,但这不起作用。
问候。
答案 0 :(得分:2)
awk 解决方案:
awk '/^ABC.*:/{ abc=$0 }$0~/"count"/{ gsub(/[^0-9]+/,"",$0); print abc" , "$0 }' file
输出:
ABC:9804 , 492
ABC:95023 , 865
ABCC:128 , 479
答案 1 :(得分:0)
<强> 输入 强>
$ cat infile
ABC:9804
{
"count" : 492,
"_shards" : {
"total" : 19,
"successful" : 19,
"failed" : 0
}
}
Bye
ABC:95023
{
"count" : 865,
"_shards" : {
"total" : 19,
"successful" : 19,
"failed" : 0
}
}
Bye
ABCC:128
{
"count" : 479,
"_shards" : {
"total" : 19,
"successful" : 19,
"failed" : 0
}
}
Bye
<强> 输出 强>
<强> Gawk的强>
$ awk -F':' -v RS='[{},\n]' '/ABC.*|\"count"/{gsub(/[\n\t ]+/,""); printf /\"/? ", " $2 "\n": $0}' infile
ABC:9804, 492
ABC:95023, 865
ABCC:128, 479
更好的可读性
awk -F':' -v RS='[{},\n]' '
/ABC.*|\"count"/{
gsub(/[\n\t ]+/,"");
printf /\"/? ", " $2 "\n": $0
}
' infile
<强>非GAWK 强>
$ awk -F'[ ,]' -v OFS=", " '/^[ \t]+(ABC.*|\"count\"[ ]?):/{ sub(/^[ \t]+/,""); printf /\"/ ? OFS $(NF-1) RS: $0 }' infile
ABC:9804, 492
ABC:95023, 865
ABCC:128, 479
更好的可读性
awk -F'[ ,]' -v OFS=", " '
/^[ \t]+(ABC.*|\"count\"[ ]?):/{
sub(/^[ \t]+/,"");
printf /\"/ ? OFS $(NF-1) RS: $0
}
' infile