Search code examples
macossedinsertwhitespacebsd

insert new line with leading whitespace using sed on osx


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?


Solution

  • 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