13

When I try to insert new line in OSX using sed I'm getting the below error

extra characters after \ at the end of a command

Current File content is

{
'localhost' => ['domain_name' => 'default', 'domain_type' => 'mobile'],
}

Expected content is

{
'localhost' => ['domain_name' => 'default', 'domain_type' => 'mobile'],
 'dev.ops' => ['domain_name' => 'default', 'domain_type' => 'mobile'],
}

The command I'm using is

sed -i '' "/localhost/a\                        'dev.ops' => ['domain_name' => 'default', 'domain_type' => 'web']," FILENAME
Inian
  • 80,270
  • 14
  • 142
  • 161
  • 2
    Possible duplicate of [sed insert line command OSX](http://stackoverflow.com/questions/25631989/sed-insert-line-command-osx) – Inian Nov 28 '16 at 12:31

2 Answers2

25

BSD/macOS sed requires an actual newline character to follow a\, before the text to append:

sed -i '' "/localhost/ a\\
                        'dev.ops' => ['domain_name' => 'default', 'domain_type' => 'web'],
" FILENAME
  • Since you're using "..." to enclose your sed script, a\ must be represented as a\\ so that the \ is not mistaken for a line continuation character.
    • It is generally better to use '...' to enclose your script argument, but here the use of "..." is convenient for easy embedding of ' instances.

As an aside: GNU sed - installable on macOS via Homebrew using brew install gnu-sed - offers more features and more convenient syntax - notably, no need for a newline to follow the a function; for a discussion of all differences between BSD/macOS sed and GNU sed, see this answer of mine.

mklement0
  • 382,024
  • 64
  • 607
  • 775
  • 3
    I solved this problem permanently by installing gnu-sed. brew install gnu-sed and use "gnu-sed" as "sed" by adding a "gnubin" directory to PATH from ~/.bash_profile like this: export PATH="/usr/local/opt/gnu-sed/libexec/gnubin:$PATH". Thanks @mklement0 – Dilip Dalwadi Apr 29 '20 at 12:32
3

Use sed p command to copy line and then replace the

sed '/localhost/p; s/localhost/dev.ops/' FILENAME

outputs

{
'localhost' => ['domain_name' => 'default', 'domain_type' => 'mobile'],
'devops' => ['domain_name' => 'default', 'domain_type' => 'mobile'],
}

or to edit in place on OSX without keeping a backup, use -i '':

sed -i '' -e '/localhost/p; s/localhost/dev.ops/' FILENAME
mklement0
  • 382,024
  • 64
  • 607
  • 775
VladimirAus
  • 181
  • 1
  • 4