1

I am trying to write a script to reformat some text.

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 

The expected output would be

 '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 

Using this 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" I get this:

 '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 
2
  • I'd suggest using a YAML parsing tool such as kislyuk's yq rather than a text processing tool - for example something like yq -Y '.pages[] | .items | with_entries(.value |= {"type": "item", "item": {material}, "buyPrice": .buy, "sellPrice": .sell} | .value += {"slot": .key | tonumber})' file.ymlCommentedDec 7, 2023 at 2:39
  • When I run your pipeline of seds I get sed: -e expression #1, char 25: unterminated s' command`
    – Ed Morton
    CommentedDec 7, 2023 at 15:45

1 Answer 1

-1

Using any 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 

    You must log in to answer this question.

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.