sed往指定位置插入变量的小技巧

sed中的常用往后插入的语法,比如往匹配到的行后面添加内容,可以使用-i参数和a参数来往后插入

[root@linux ~#] sed -i '/Pattern/ a\String' FileName

如果要插入的是个变量,则需要将注意两点:

  • 使用双引号来替代单引号
  • 使用反斜杠对\进行转译

下面就是个示例。示例文件: 1.txt,要往第四行后面添加字符串var="New Line Here."

This is line 1.
This is line 2.
This is line 3.
This is line 4.
This is line 5.
This is line 6.

 就可以这样做:

[root@linux ~#] var="New Line Here."
[root@linux ~#] sed -i "/This is line 4/ a\\$var" 1.txt
This is line 1.
This is line 2.
This is line 3.
This is line 4.
New Line Here.
This is line 5.
This is line 6.

 

你可能感兴趣的:(【编程语言】)