Reputation: 101
I have this code:
sed -i -s "1i${var}" $file
I need to copy all the content of the variable var
into the top of the file without deleting the content of the file. When var
has one line, the command works well, but when var
has multiple lines I get this error:
sed: -e expression #1, character 28: extra characters after command
I need to use sed.
Any idea?
Thanks.
Upvotes: 1
Views: 1204
Reputation: 4267
if $var has line breaks, sed will give error you need append '\' after each line if you want to insert multiple lines
$ echo abc | sed -e '1iinsert 1st line
2nd line'
sed: -e expression #1, char 21: extra characters after command
$ echo abc | sed -e '1iinsert 1st line\
2nd line'
insert 1st line
2nd line
abc
man sed
search for insert
i \ text Insert text, which has each embedded newline preceded by a back- slash.
Upvotes: 3
Reputation: 60143
You have to take into account the fact that sed
does not expand the ${var}
part.
Bash does. Sed receives a string where ${var}
has already been replaced with the actual content of $var
.
You need to make sure such substitution will result in a valid sed
command.
Upvotes: 2