1

I have followed instructions in this post How to insert text after a certain string in a file?

but I suspect the instructions are not valid for OSX.

I want to add some text into a source file using Bash

sed '/pattern/a some text here' ${sourceFile}

but when I run the command I get

"/pattern/a some text here": command a expects \ followed by text

edit

I have created a new file called infile with a single line

pattern

and a bash script

#!/bin/bash
sed '/pattern/a\
text to insert' infile

running the script echos "pattern" to the console but doesn't insert the text

edit

I have also tried for the bash script

#!/bin/bash
sed '/pattern/a\
add one line\
\\and one more' infile

and the terminal echos

pattern
add one line
\and one more

but infile still has single line

pattern
the_prole
  • 457

2 Answers2

1

I'm not sure if OSX has ed (found one positive hint), so here's another option:

grep -q pattern infile && ed -s infile  <<< $'/pattern/\na\ntext to insert\n.\nw\nq' > /dev/null

This sends the following commands to ed:

  1. /pattern/ -- search for "pattern"
  2. a -- append the following text after that line
  3. text to insert -- the text
  4. . -- end of the inserted text
  5. w -- write the updated file to disk
  6. q -- quit ed

The >/dev/null redirection is to silence ed's report of the matching pattern line.

I've prefixed the ed command with a quiet grep to ensure that "pattern" exists in the file before asking ed to search for it -- otherwise, you'll get a confused ? from ed when the pattern search fails.

Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255
  • The problem is the command doesn't seem to work with double quotes so I don't appear to be able to perform string interpolation $'/pattern/\na\ntext to insert\n.\nw\nq' – the_prole Jan 20 '19 at 22:14
  • start and end the interpolation where you want to insert text: $'/pattern/...'"your text here"$'\n.\nw\nq' – Jeff Schaller Jan 20 '19 at 22:24
1

You forgot to use the -i the in-place editing option of sed. Because sed is a stream editor so will not make any changes to the input. You need to explicitly make the efforts to move the output file back to the input or use the -i option if available:

#!/bin/bash
sed -i '' -e '/pattern/a\
add one line\
\\and one more' \
infile