简体   繁体   中英

Sed error in bash shell script

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.

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. 

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM