Sed 带空格的插入行指向一个特定的行

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

hello
world

结果:

hello
hello world
world

我正在使用这个 sed 脚本:

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

问题是我的新系列没有空格:

hello
hello world
world
104639 次浏览

You can escape the space character, for example to add 2 spaces:

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

Or you can do it in the definition of your text variable:

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

The . was added in the substitution above to demonstrate that the trailing whitepsaces are preserved. Use sed "/world/ s/.*/${a}\n&/" instead.

You only need one \ to input multiple blanks like this

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

It can be done by splitting the expression like this:

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

This is a GNU extension for easier scripting.