[英]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. 我需要将变量
var
所有内容复制到文件的顶部,而不删除文件的内容。 When var
has one line, the command works well, but when var
has multiple lines I get this error: 当
var
有一行时,该命令运行良好,但是当var
有多行时,出现此错误:
sed: -e expression #1, character 28: extra characters after command
I need to use sed. 我需要使用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 如果$ var有换行符,sed将给出错误,如果要插入多行,则需要在每行后附加'\\'
$ 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 man sed
搜索插入
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. 您必须考虑到
sed
不会扩展${var}
部分的事实。 Bash does. 巴什做。 Sed receives a string where
${var}
has already been replaced with the actual content of $var
. Sed接收一个字符串,其中
${var}
已被$var
的实际内容替换。 You need to make sure such substitution will result in a valid sed
command. 您需要确保这样的替换将导致有效的
sed
命令。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.