Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Insert a text with indentation persevered on the next line of matched string

I have a file with a yaml data as below:

cat x.yml
foo:
 - bar: 1
 - zoo: 2

I am able to insert the text but this is messing the indentation(see 2nd line):

sed -r '/^[ ]+- bar:/a- hoo: 3' x.yml
foo:
 - bar: 1
- hoo: 3
 - zoo: 2

Then, I tried to backreference the leading spaces but seems like it is not working with /a flag.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

sed -r '/^([ ]+)- bar:/a\1- hoo: 3' x.yml
foo:
 - bar: 1
1- hoo: 3
 - zoo: 2

Any help to get the following using a one-liner ?

foo:
 - bar: 1
 - hoo: 3
 - zoo: 2

>Solution :

I suggest to switch to GNU sed’s s command:

sed -E 's/( *)- bar:.*/&\n\1- hoo: 3/' file

Output:

foo:
 - bar: 1
 - hoo: 3
 - zoo: 2

See: man sed and The Stack Overflow Regular Expressions FAQ

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading