0

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 portable way to do it (with any sed, including the OSX one) is in my post there... – don_crissti Jan 20 at 21:19
  • If the pattern matches a string in the infile, terminal echos print statment, but print statement is not inserted into infile awk '1;/pattern/{ print "add one line"; print "\\and one more"}' infile – the_prole Jan 20 at 21:32
  • this is true of sed example as well – the_prole Jan 20 at 21:35
  • You need to save the edits with the -i option to sed. Otw, save it to a temp file nd move it back to the original file. – Rakesh Sharma Jan 21 at 2:09
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.

  • 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 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 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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.