0

I have Front Matter files like this:

---
title: BMW i320 M3 150HP Petrol 2020
category: sportscar
color: metal
---

MD content Starts Here
Lorem ipsum Lorem Ipsum Lorem Ipsun
Lorem ipsum Lorem Ipsum Lorem Ipsun

Using kislyuk's python-yq, I managed to accomplish my goal using following command:

yq -i -y '
    if (.category=="sportscar") and (.title | contains(" Petrol")) then
        .engine = "fuel"
      elif (.category=="sportscar") and (.title | contains(" Gasoline")) then
        .engine = "fuel"
      elif (.category=="sportscar") and (.title | contains(" Diesel")) then
        .engine = "fuel"
      elif (.category=="sportscar") and (.title | contains(" Ethanol")) then
        .engine = "fuel" 
      elif (.category=="sportscar") and (.title | contains(" Aviation Gas")) then
        .engine = "fuel"
      else
        .engine = "electric"
      end' *

THIS WORKS ONLY IF MD FILE HAVE NO CONTENT BELLOW --- And I cant lose this content.

So I went to mikefarah's yq version. Because of that --front-matter=process option.

Actually this can process the md files, without mess with the content part But this yq version dont work with If Elif Else approach.

So it throws me this error:

Error: parsing expression: Lexer error: could not match text starting at 1:6 failing at 1:8.
    unmatched text: "if"

How can i make this conditional approach, without lose the content part of MD Files? I have more than 2000 files to manage.... +80% has content bellow ---

I need this final scenario:

---
title: BMW i320 M3 150HP Petrol 2020
category: sportscar
color: metal
engine: fuel
---

MD content Starts Here
Lorem ipsum Lorem Ipsum Lorem Ipsun
Lorem ipsum Lorem Ipsum Lorem Ipsun

Inian
  • 80,270
  • 14
  • 142
  • 161

1 Answers1

1

mikefarah/yq does not have an explicit if-then-else construct available as part of its DSL, but it can be emulated using cascading with(..) conditions as below

yq -f process '(
  with(select(.category=="sportscar" and .title |
    (contains("Petrol") or contains("Diesel") or contains("Ethanol") or contains("Aviation Gas")));
    .engine = "fuel"
  ) |
  with(select(.category=="sportscar" and .title |
    ((contains("Petrol") or contains("Diesel") or contains("Ethanol") or contains("Aviation Gas")) | not));
    .engine = "electric"
  )
)' yaml

Tested on version 4.24.2 (current latest release). Add the in-place replacement flag (-i) once you verify the contents are processed as expected in a few files.

Inian
  • 80,270
  • 14
  • 142
  • 161