我想在文件中间插入一些文本。要插入的文本将在特定行之后,例如“ <begin>”。我不知道行号,也不知道要插入的文本行数。我只知道在读取“ <begin>”的行之后,我需要插入另一个文件的内容。
我只是不知道如何使用 awk 来做这样的事情。
谢谢 :-)
/<begin>/{
insert_file("before_file.html")
print $0
insert_file("after_file.html")
next
}
{
print $0
}
Run Code Online (Sandbox Code Playgroud)
您必须在其中编写insert_file可能看起来像的函数
function insert_file(file) {
while (getline line <file)
print line
close(file)
}
Run Code Online (Sandbox Code Playgroud)
请注意,当 before_file 和 after_file 相同时,这个确切版本在我的 Mac 上似乎没有按预期工作......我只得到了唯一的第一个副本。这可能与未能关闭文件有关。我会调查的。是的,close文件是必要的,并且通常应该这样做以获得良好的实践。
另外,我认为这可能更容易sed......
用于在关键行之后插入文件
sed '/<begin>/r after_file.html' input_file
Run Code Online (Sandbox Code Playgroud)
之前插入文件有点复杂,
sed -n -e '/^function/r before_file.html' -e 'x' -e 'p' input_file
Run Code Online (Sandbox Code Playgroud)
所以你可以使用像这样的脚本
/^function/r before_file.html
x
p
Run Code Online (Sandbox Code Playgroud)
和
sed -n -f script input_file
Run Code Online (Sandbox Code Playgroud)