Milan Lenco
Milan Lenco

Reputation: 95

Bash, sed: replacing pattern with multiline file content

if I have file named some_file, with content as follows:

first line 
second line 
third line

and inside script:

VAR1="first line\nsecond line\nthird line"
VAR2="`cat some_file`"

I expect VAR1 and VAR2 to be the same, but it is obviously not the case according to the sed:

sed "s/^a/${VAR1}/" some_another_file # this is OK
sed "s/^a/${VAR2}/" some_another_file # this fail with syntactic error

I suppose that newline representation is somehow different, but i can't find any way how to make VAR2 equal to VAR1.

thanks in advance

Upvotes: 2

Views: 4083

Answers (2)

Dennis Williamson
Dennis Williamson

Reputation: 359875

This will read in the file and replace the line with its contents:

sed -e '/^a/{r some_file' -e 'd}' some_another_file 

Upvotes: 4

dogbane
dogbane

Reputation: 274532

Change VAR1 to:

VAR1=$(echo -e "first line\nsecond line\nthird line")

Then test them:

$ [ "$VAR1" == "$VAR2" ] && echo equal
equal

Update:

To get sed to work, change VAR2 so that it has "\n"s instead of newline characters.

VAR2=$(sed ':a;N;$!ba;s/\n/\\n/g' some_file)
sed "s/^a/${VAR2}/" file

Upvotes: 2

Related Questions