如何在文件中的某个字符串后插入文件内容?

yae*_*ael 2 sed awk perl shell-script text-processing

我们有例如这个文件

cat exam.txt

I am expert linux man
what we can do for out country
I love redhat machine
"propertie"
centos less then redhat
fedore what
my name is moon yea
Run Code Online (Sandbox Code Playgroud)

我们想在属性行之后添加任何文件的内容作为 file.txt

cat file.txt

324325
5326436
3245235
646346
545
643
6436
63525
664
46454
Run Code Online (Sandbox Code Playgroud)

所以我尝试以下操作:

a=` cat file `

sed -i '/propertie/a  `echo "$a"` ' exam.txt
Run Code Online (Sandbox Code Playgroud)

但不起作用

有什么建议可以使用 sed/awk/perl 一行来在某个字符串后添加文件内容?

预期产出

I am expert linux man
what we can do for out country
I love redhat machine
"propertie"
    324325
    5326436
    3245235
    646346
    545
    643
    6436
    63525
    664
    46454
centos less then redhat
fedore what
my name is moon yea
Run Code Online (Sandbox Code Playgroud)

Kus*_*nda 8

您几乎从不想将文件的完整内容存储在 Unix shell 脚本的变量中。如果你发现自己这样做了,问问自己是否还有其他解决方案。如果你自己找不到,请来这里,我们会看看:-)


$ sed '/propertie/r file.txt' exam.txt
I am expert linux man
what we can do for out country
I love redhat machine
"propertie"
324325
5326436
3245235
646346
545
643
6436
63525
664
46454
centos less then redhat
fedore what
my name is moon yea
Run Code Online (Sandbox Code Playgroud)

r在(“读取”)命令sed将文件名作为其参数,并插入该文件的内容插入到当前流。

如果您需要缩进添加的内容,请确保file.txt在运行之前缩进的内容sed

$ sed 's/^/    /' file.txt >file-ind.txt
$ sed '/propertie/r file-ind.txt' exam.txt
I am expert linux man
what we can do for out country
I love redhat machine
"propertie"
    324325
    5326436
    3245235
    646346
    545
    643
    6436
    63525
    664
    46454
centos less then redhat
fedore what
my name is moon yea
Run Code Online (Sandbox Code Playgroud)

With ed(要求sed对插入的文件进行缩进)。这也会对文件进行就地编辑,并用修改后的内容替换原始文件。

ed -s exam.txt <<END_ED
/propertie/r !sed 's/^/    /' file.txt
wq
END_ED
Run Code Online (Sandbox Code Playgroud)

r命令ed能够读取的外部命令的输出指令是否前缀!。我们使用它来缩进我们想要插入的数据。否则,出于显而易见的原因,它与上述sed解决方案非常相似。

使用的唯一缺点ed是您通常不能在非常大的文件上使用它。 sed用于编辑不确定长度的流,而ed用于编辑您可以看到自己在任何其他编辑器中打开的文档,即不是许多兆字节或千兆字节大小的文件。