2

I am trying to use this expression to insert the contents of one text file into another after a give string. This is a simple bash script:

    TEXT=`cat file1.txt`
    sed -i "/teststring/a \
    $TEXT" file2.txt

This returns an error, "sed: -e expression #1, char 37: unknown command: `M'"

The issue is in the fact that the contents of file1.txt are actually a private certificate so it's a large amount of text and unusual characters which seems to be causing an issue. If I replace $TEXT with a simple ASCII value it works but when it reads the large content of file1.txt it fails with that error.

Is there some way to carry out this action? Is my syntax off with sed or my quote placement wrong?

2 Answers 2

6

Use r to read the certificate file, not a to append the string -- sed is confused because you'd first need to escape newlines and special characters in the string to append. You do not need to escape any text in the file -- sed just reads and appends it.

sed -i "/teststring/r file1.txt" file2.txt
1
  • Thank you, this works perfect! Glad you helped, I learned more about sed now, I also read the man, makes more sense now, thanks a ton!
    – Luis Varca
    Oct 29, 2013 at 20:58
2

I would use ed editor. It's like vi but for command line.

Example:

$ echo foobar > /tmp/orig
$ cat > /tmp/add << EOF
> blablabla
> blablabla
> blablabla
> EOF
$ printf "/foobar\n.r /tmp/add\nwq\n" | ed /tmp/orig
7
foobar
30
37
$ cat /tmp/orig
foobar
blablabla
blablabla
blablabla
3
  • Well, ex is like vi for the command line. ed is a predecessor
    – mpez0
    Oct 29, 2013 at 15:54
  • And is it installed by default on AIX, Solaris, BSD world? :)
    – jirib
    Oct 29, 2013 at 16:12
  • This works, I ended up using the sed solution below but thank you, I love to learn alternate methods.
    – Luis Varca
    Oct 29, 2013 at 20:59

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .