skip to Main Content

I have an yaml object like below

input="poc_string: 'This is my succeeding string!'
poc_fail: false"

I want to convert this to the string below

'{"poc_string":"This is my succeeding string!","poc_fail":false}'

The following has to change

  • single qoutes aroung This is my succeeding string! to double quotes
  • all strings before and after : except true or false should get enclosed in double quotes " "
  • the new line should be replaced with a comma ,. However, if the new line is the very end, , should not be inserted.

This needs to be done in sed
I am new to sed and bash in general so, I have started with the below command (going one by one)

output=$(echo $sql | sed -r "s/'/"/g" | sed -r "s/: /:/g"| sed -rE "s/(w*):/"&"/g")
echo $output
  • First, I replaced ' with ", worked fine
  • Second, replaced spaces after :, worked fine
  • Now, trying to wrap all text before : with quotes and it doesn’t work.

my output as of now is poc_string:'This is my succeeding string!' poc_fail:false

How to get the output I desire?

ps: I am working with ubuntu 22.04.3 (it was mentioned in some online artifacts the OS is important)

2

Answers


  1. This might work for you (GNU sed):

     sed -E 'H;1h;$!d;x
             s/^(.*): '''?([^''']*)'''?$/"1":"2"/mg
             s/"(true|false)"/1/mg
             y/n/,/' file
    

    Slurp the file into memory.

    Use pattern matching to surround keys and values by double quotes and remove a space.

    Return true and false values as were.

    Replace newlines by ,‘s

    Login or Signup to reply.
  2. Instead of using sed, you might want to consider using something that has a real YAML parser, for example yq.

    Or you could use Python:

    python3 -c 'import json, yaml, sys; json.dump(yaml.safe_load(sys.stdin), sys.stdout)'
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search