一部のテキストの書式を再指定するスクリプトを作成しようとしています。
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