Linux sed 将带有空格的行插入到特定行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18439528/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
sed insert line with spaces to a specific line
提问by Yo Al
I have a line with spaces in the start for example " Hello world". I want to insert this line to a specific line in a file. for example insert " hello world" to the next file
我在开头有一行空格,例如“Hello world”。我想将此行插入文件中的特定行。例如在下一个文件中插入“hello world”
hello
world
result:
结果:
hello
hello world
world
I am using this sed script:
我正在使用这个 sed 脚本:
sed -i "${line} i ${text}" $file
the problem is that i am getting my new line with out the spaces:
问题是我的新行没有空格:
hello
hello world
world
采纳答案by Atropo
You can escape the space
character, for example to add 2 spaces:
您可以对space
字符进行转义,例如添加 2 个空格:
sed -i "${line} i \ \ ${text}" $file
Or you can do it in the definition of your text
variable:
或者您可以在text
变量的定义中执行此操作:
text="\ \ hello world"
回答by devnull
$ 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.
的.
是在上述取代加到证明尾随whitepsaces被保留。使用sed "/world/ s/.*/${a}\n&/"
来代替。
回答by LeoChu
You only need one \
to input multiple blanks
like this
你只需要一个\
这样输入多个空格
sed -i "${line} i \ ${text}" $file
回答by dashohoxha
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.
这是一个 GNU 扩展,用于简化脚本编写。