user3570398
user3570398

Reputation: 345

Add multiple lines in file using bash script

Using a bash script, I am trying to insert a line in a file (eventually there will be 4 extra lines, one after the other).

I am trying to implement the answer by iiSeymour to the thread:

Insert lines in a file starting from a specific line

which I think is the same comment that dgibbs made in his own thread:

Bash: Inserting a line in a file at a specific location

The line after which I want to insert the new text is very long, so I save it in a variable first:

field1=$(head -2 file847script0.xml | tail -1)

The text I want to insert is:

insert='newtext123'

When running:

sed -i".bak" "s/$field1/$field1\n$insert/" file847script0.xml 

I get the error:

sed: 1: "s/<ImageAnnotation xmln ...": bad flag in substitute command: 'c'

I also tried following the thread

sed throws 'bad flag in substitute command'

but the command

sed -i".bak" "s/\/$field1/$field1\n$insert/" file847script0.xml

still gives me the same error:

sed: 1: "s/\/<ImageAnnotation xm ...": bad flag in substitute command: 'c'

I am using a Mac OS X 10.5.

Any idea of what am I doing wrong? Thank you!

Upvotes: 3

Views: 4976

Answers (2)

Ed Morton
Ed Morton

Reputation: 204638

Good grief, just use awk. No need to worry about special characters in your replacement text or random single-character commands and punctuation.

In this case it looks like all you need is to print some new text after the 2nd line so that's just:

$ cat file
a
b
c

$ insert='absolutely any text you want, including newlines
slashes (/), backslashes (\\), whatever...'

$ awk -v insert="$insert" '{print} NR==2{print insert}' file
a
b
absolutely any text you want, including newlines
slashes (/), backslashes (\), whatever...
c

Upvotes: 2

nic ferrier
nic ferrier

Reputation: 1660

Isn't it easier to do it by line number? If you know it's the second line or the nth line (and grep will tell you line numbers if you are pattern matching) then you can simply use sed to find the correct line and then append a new line (or 4 new lines).

cat <<EOF > testfile
one two three
four five six
seven eight nine
EOF

sed -re '2a\hello there' testfile

will output

one two three
four five six
hello there
seven eight nine

Upvotes: 0

Related Questions