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
:
excepttrue
orfalse
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
This might work for you (GNU sed):
Slurp the file into memory.
Use pattern matching to surround keys and values by double quotes and remove a space.
Return
true
andfalse
values as were.Replace newlines by
,
‘sInstead of using
sed
, you might want to consider using something that has a real YAML parser, for exampleyq
.Or you could use Python: