sed将空格插入到特定行

时间:2013-08-26 08:10:59

标签: linux bash sed

我在开头有一行空格,例如“Hello world”。 我想将此行插入文件中的特定行。 例如 将“hello world”插入下一个文件

hello
world

结果:

hello
    hello world
world

我正在使用这个sed脚本:

sed -i "${line} i ${text}" $file

问题是我在空格中得到了我的新行:

hello
hello world
world

4 个答案:

答案 0 :(得分:64)

您可以转义space字符,例如添加2个空格:

sed -i "${line} i \ \ ${text}" $file

或者您可以在text变量的定义中执行此操作:

text="\ \ hello world"

答案 1 :(得分:16)

您只需要一个\来输入多个空格 像这样

sed -i "${line} i \    ${text}" $file

答案 2 :(得分:4)

$ a="  some string  "
$ echo -e "hello\nworld"
hello
world
$ echo -e "hello\nworld" | sed "/world/ s/.*/${a}.\n&/" 
hello
  some string  .
world

在上面的替换中添加了.,以证明尾随的whitepsaces被保留。请改用sed "/world/ s/.*/${a}\n&/"

答案 3 :(得分:0)

可以通过如下拆分表达式来完成:

sed -i $file -e '2i\' -e "     $text"

这是GNU扩展,可简化脚本编写。