我正在尝试编写一个脚本来重新格式化某些文本。
pages:
page1:
gui-rows: 6
items:
'6':
material: CAT_SPAWN_EGG
buy: 999999999
sell: -1
'7':
material: CAVE_SPIDER_SPAWN_EGG
buy: 999999999
sell: -1
page2:
gui-rows: 6
'8':
material: CHICKEN_SPAWN_EGG
buy: 999999999
sell: -1
预期输出是
'6':
type: item
item:
material: CAT_SPAWN_EGG
buyPrice: 999999999
sellPrice: -1
slot: 6
'7':
type: item
item:
material: CAVE_SPIDER_SPAWN_EGG
buyPrice: 999999999
sellPrice: -1
slot: 7
'8':
type: item
item:
material: CHICKEN_SPAWN_EGG
buyPrice: 999999999
sellPrice: -1
slot: 8
使用这个cat 0.yml | sed "/page.*/d" | sed "/gui-row.*/d" | sed "/item.*/d" | sed "s/ / /g" | sed "s/.*':/&\\n type: item\\n item:/g" | sed "s/material.*/ &/g" |sed "s/buy/buyPrice/g" | sed "s/sell/sellPrice/g" | sed "s/sell.*/&\n slot: X"
我得到这个:
'6':
type: item
item:
material: CAT_SPAWN_EGG
buyPrice: 999999999
sellPrice: -1
slot: X
'7':
type: item
item:
material: CAVE_SPIDER_SPAWN_EGG
buyPrice: 999999999
sellPrice: -1
slot: X
'8':
type: item
item:
material: CHICKEN_SPAWN_EGG
buyPrice: 999999999
sellPrice: -1
slot: X
答案1
使用任何 POSIX awk:
$ cat tst.awk
{ gsub(/^[[:space:]]+|[[:space:]]+$/,"") }
match($0,/^[^:]+:/) {
tag = substr($0,1,RLENGTH-1)
val = substr($0,RSTART+RLENGTH)
sub(/[[:space:]]+$/,"",tag)
sub(/^[[:space:]]+/,"",val)
if ( gsub(/\047/,"",tag) ) {
prt()
val = tag
tag = "slot"
}
t2v[tag] = val
}
END { prt() }
function prt( indent) {
indent = 4
printf "%*s\047%s\047:\n", indent, "", t2v["slot"]
indent += 2
printf "%*s%s: %s\n", indent, "", "type", "item"
printf "%*s%s:\n", indent, "", "item"
indent += 2
printf "%*s%s: %s\n", indent, "", "material", t2v["material"]
indent -= 2
printf "%*s%s: %s\n", indent, "", "buyPrice", t2v["buy"]
printf "%*s%s: %s\n", indent, "", "sellPrice", t2v["sell"]
printf "%*s%s: %s\n", indent, "", "slot", t2v["slot"]
delete t2v
}
$ awk -f tst.awk 0.yml
'6':
type: item
item:
material: CAT_SPAWN_EGG
buyPrice: 999999999
sellPrice: -1
slot: 6
'7':
type: item
item:
material: CAVE_SPIDER_SPAWN_EGG
buyPrice: 999999999
sellPrice: -1
slot: 7
'8':
type: item
item:
material: CHICKEN_SPAWN_EGG
buyPrice: 999999999
sellPrice: -1
slot: 8