1

How can I use a cat and sed to read data from a file and insert it into another file under known line?

For example I have a file named script1.txt that contains a few hundred lines, one of the line has the value "COMMANDS="commands"

If I wanted use sed to insert a line under it, simply I can use sed as the command bellow.

sed -i '/^COMMANDS=.*/a NEW LINE HERE' script1.txt

But if I want to insert a multi lines and these lines inside a file, and these line changes every a few hours.. how can i do that ?

I tried:

DATA=$(cat data.txt)

sed -i '/^COMMANDS=.*/a '$DATA'' script1.txt

I got the error bellow.

sed: -e expression #1, char 1: unknown command: `"'

Is there a way other than sed to insert the data from file under known line with no issues?

2 Answers 2

2

This might work for you (GNU sed):

sed -i '/^COMMANDS=/r dataFile' file

This will append the contents of the file dataFile after the line beginning COMMANDS= and update file

0
1

If the data you want to append is multi-line, you might want to replace newlines with \n.

#!/bin/sh
DATA="$(awk '{gsub(/[]\/$*.^&[]/, "\\\\&");printf (FNR>1)?"\\n%s":"%s",$0}END{print ""}' data.txt)"
sed -i -e '/^COMMANDS=.*/a\' -e "$DATA" script1.txt

Here the awk command escapes sed special characters (for basic regular expressions), then prints "%s" for the first line, and "\\n%s" for the others. A newline is printed at the end, but it's somewhat pointless as $() strips it anyway.

The sed command is almost the same but multiple expressions are used which is equivalent to a multi-line sed script (The a text sed alternative syntax can act weirdly with leading spaces/backslashes).

1
  • i'll give it a try later. Thank you
    – Ayad
    Commented Jul 23, 2019 at 21:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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