Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I sort a yaml file based on the value of a particular key

Part 1 : I have a yaml file with many blocks defining input text and the text its replaces with. Each block has a trigger key and the value of that trigger, a replacement key and the value the trigger is replaced with and a comment line: e.g.

# ::;waf::web application firewall
  - trigger: ";waf"
    replace: "web application firewall"

# ::;m$::Microsoft
  - trigger: ";m$"
    replace: "Microsoft"

# ::;sf::Salesforce
  - trigger: ";sf"
    replace: "Salesforce"

I'd like to sort the blocks into order based on the value of the trigger key

# ::;m$::Microsoft
  - trigger: ";m$"
    replace: "Microsoft"

# ::;sf::Salesforce
  - trigger: ";sf"
    replace: "Salesforce"

# ::;waf::web application firewall
  - trigger: ";waf"
    replace: "web application firewall"

If the comments mess things up then I can use a reg exp to move the comment from a preceding line to an inline comment on the end of the trigger line. What I'm trying to avoid is using a regexp to turn the three lines into one, then sort, then split back into three lines again because...

...Part 2: I have a similar file, again with many blocks. Each block has AT LEAST a trigger key, a replacement key and a comment line but may also have other key value pairs as well. Each block always starts with a trigger. I'd like to sort the blocks into order based on the value of the trigger key but keep the blocks. Doing a regexp to concatenate an unknown and variable number of key value pairs is making my head hurt.

My chosen editor is VScodium, I tried the YAML sort extension but it sorts on the key names, not the key values or at least it does for how I've got it configured. I'm happy with a solution in bash, sed, awk or whatever but one-liners (as opposed to a full multiline code block with nested loops) would be preferred if possible. I want to see what the most elegant/efficient way of achieving this is. Please :-)

like image 903
Curious User Avatar asked Oct 25 '25 21:10

Curious User


1 Answers

keep-sorted can handle this:

  # keep-sorted start
  - # ::;waf::web application firewall
    trigger: ";waf"
    replace: "web application firewall"

  - # ::;m$::Microsoft
    trigger: ";m$"
    replace: "Microsoft"

  - # ::;sf::Salesforce
    trigger: ";sf"
    replace: "Salesforce"
  # keep-sorted end

Source: example setup.

like image 198
thiagowfx Avatar answered Oct 27 '25 11:10

thiagowfx