简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM