bash 使用sed插入文件内容
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11243102/
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
Using sed to insert file content
提问by ridan
I'm trying to insert a file content before a given pattern
我正在尝试在给定模式之前插入文件内容
Here is my code:
这是我的代码:
sed -i "" "/pattern/ {
i\
r $scriptPath/adapters/default/permissions.xml"
}" "$manifestFile"
It adds the path instead of the content of the file.
它添加路径而不是文件的内容。
Any ideas ?
有任何想法吗 ?
回答by Todd A. Jacobs
In order to insert text beforea pattern, you need to swap the pattern space into the hold space before reading in the file. For example:
为了在模式前插入文本,您需要在读入文件之前将模式空间交换到保持空间。例如:
sed "/pattern/ {
h
r $scriptPath/adapters/default/permissions.xml
g
N
}" "$manifestFile"
回答by Igor Chubin
Just remove i\\.
只需删除i\\.
Example:
例子:
$ cat 1.txt
abc
pattern
def
$ echo hello > 2.txt
$ sed -i '/pattern/r 2.txt' 1.txt
$ cat 1.txt
abc
pattern
hello
def
回答by benok
I tried Todd's answer and it works great,
我试过托德的回答,效果很好,
but I found "h" & "g" commands are ommitable.
但我发现“h”和“g”命令是可以省略的。
Thanks to this faq(found from @vscharf's comments), Todd's answer can be this one liner.
多亏了这个常见问题(从@vscharf 的评论中找到),托德的答案可以是这个班轮。
sed -i -e "/pattern/ {r $file" -e 'N}' $manifestFile
Edit:If you need here-doc version, please check this.
编辑:如果您需要此处的文档版本,请检查此.
回答by bcelary
I got something like this using awk. Looks ugly but did the trick in my test:
我使用 awk 得到了这样的东西。看起来很丑,但在我的测试中做到了:
command:
命令:
cat test.txt | awk '
/pattern/ {
line = $ cat test.txt
some stuff
pattern
some other stuff
;
while ((getline < "insert.txt") > 0) {print};
print line;
next
}
{print}'
test.txt:
测试.txt:
$ cat insert.txt
this is inserted file
this is inserted file
insert.txt:
插入.txt:
some stuff
this is inserted file
this is inserted file
pattern
some other stuff
output:
输出:
sed -i '/pattern/ i\
INSERTION_MARKER
' $manifestFile
sed -i '/INSERTION_MARKER/r $scriptPath/adapters/default/permissions.xml' $manifestFile
sed -i 's/INSERTION_MARKER//' $manifestFile
回答by Sinhyeok
CodeGnome's solution don't work, if the pattern is on the last line.. So I used 3 commands.
CodeGnome 的解决方案不起作用,如果模式在最后一行。所以我使用了 3 个命令。
##代码##
