I have a YAML file for a Ruby on Rails configuration that is formatted like the below
default: &default
api:
my_id: test
my_secret: test
development:
<<: *default
api:
domain: some domain
sso:
url: some_url
qa:
<<: *default
api:
I would like to write a script that will add a new line above all the top level elements. So for instance when the script or command runs against the above, it would produce
default: &default
api:
my_id: test
my_secret: test
development:
<<: *default
api:
domain: some domain
sso:
url: some_url
qa:
<<: *default
api:
However when I run this command
perl -pi -e 's/^^[ ](.*)$/\n$1/g' yamlfile.yml
It adds a new line above every line, not just the root elements. What would be the proper way to add such a new line above only the top level elements?
CodePudding user response:
This should achieve what you wanted :
perl -pi -e 's/^\S/\n$&/' yamlfile.yml
CodePudding user response:
^^
is redundant, and [ ]
is the opposite of what you want to match. I think you meant ^[^ ]
, which is better, but inserts a line at the top of the file.
Solution:
perl -i -pe's/^(?=\S)/\n/ if $. != 1' yamlfile.yml
A solution that reads in the whole file at once:
perl -i -0777pe's/\n\K(?=\S)/\n/g' yamlfile.yml
Neither of the above checks if there's an existing blank line. The following, on the other hand, normalizes blank lines precending top-level elements:
perl -i -0777pe's/^\n //; s/\n\K\n* (?=\S)/\n/g' yamlfile.yml