0

I have a yaml file that looks like this:

:stuff:
  - text

What I need in the end is this:

:stuff:
  - text
  - moretext

Because it's yaml it's whitespace sensitive. I've been trying to use sed to add a new line with leading whitespace and can do it with gnu sed, but I'm still struggling with osx sed.

These methods work with gnu sed, but not with osx/bsd sed.

sed -i '/- text/a\ \ - moretext'
sed -i -e '/- text/{:a;n;/^$/!ba;i\ \ - moretext' -e '}'

Edit: I understand that posix technically requires a new line after a\ but preferably this could be done in a single line?

philbert
  • 478
  • 4
  • 15

1 Answers1

4

Try this:

$ sed 's/- text/&\'$'\n''  - moretxt/' file
:stuff:
  - text
  - moretxt

Obviously it'd be simpler and more portable with awk if you can use that:

$ awk '{print} sub(/- text/,"- moretxt")' file
:stuff:
  - text
  - moretxt
Ed Morton
  • 188,023
  • 17
  • 78
  • 185
  • Thanks Ed. Took a bit of fiddling around but I got awk to work (not sed though). Some other relevant information that I left out that I was passing the argument as an inline shell provisioner with vagrant which required extra quotes around the argument that caused problems. I had to move the argument into a script like Mitchell's example here and then it worked. Cheers! https://github.com/mitchellh/vagrant/blob/91ba97f1df978ce9f23ae7a75d7c63f84211935f/website/www/Vagrantfile – philbert Jul 31 '14 at 09:08
  • This elegant `awk` example finally made me learn more about it (after avoiding it for years). Goodbye `sed`, I guess :D Thank you :) When tweaking the example for my purposes, I needed to append a custom line after a fixed string match coming from an env variable, not a regex, so I came up with this: `awk -v ma="$match" '{print} index($0, ma) {print " appended line"}' file`. It also has the benefit of not needing to match the full line above. – tlwhitec Jan 06 '21 at 11:34