如何使用 sed 将两个模式之间的多行替换为文件内容?
How to replace multiple lines between two patterns with content of a file using sed?
假设我在文件中有以下内容
file1.txt:
some text ...
...
begin
if somthing is true
some text here
...
fi
end
some text
我想用内容替换开始结束之间的文本,包括开始结束
另一个文件
file2.txt:
while read line:
do
some code
done
替换后 file1.txt 应该是这样的
file1.txt:
some text ...
...
while read line:
do
some code
done
some text
以下 awk
可能会对您有所帮助。
awk '/begin/{print;system("cat FIlE2.txt");next} 1' FIlE1.txt
输出如下。
some text ...
...
begin
while read line:
do
some code
done
if somthing is true
some text here
...
fi
end
你可以试试这个 sed
sed -e '/begin/,/end/!b' -e '/end/!d;r file2.txt' -e 'd' file1.txt
如果未指定选项 -n,则 Sed 打印文件的每一行。
在打印之前,sed 执行所有给定的 -e 选项给出的脚本。
脚本中的命令 b 告诉 sed 在此时结束脚本。
所以第一个 -e 命令告诉 sed 结束脚本并打印所有不在开头和结尾的行。
第二个 -e 命令告诉 sed 在找到带有 end.
的行时打印文件 file2.txt
第三个 -e 命令告诉 sed 删除(不打印)从开始到结束的行。
假设我在文件中有以下内容
file1.txt:
some text ...
...
begin
if somthing is true
some text here
...
fi
end
some text
我想用内容替换开始结束之间的文本,包括开始结束
另一个文件
file2.txt:
while read line:
do
some code
done
替换后 file1.txt 应该是这样的
file1.txt:
some text ...
...
while read line:
do
some code
done
some text
以下 awk
可能会对您有所帮助。
awk '/begin/{print;system("cat FIlE2.txt");next} 1' FIlE1.txt
输出如下。
some text ...
...
begin
while read line:
do
some code
done
if somthing is true
some text here
...
fi
end
你可以试试这个 sed
sed -e '/begin/,/end/!b' -e '/end/!d;r file2.txt' -e 'd' file1.txt
如果未指定选项 -n,则 Sed 打印文件的每一行。
在打印之前,sed 执行所有给定的 -e 选项给出的脚本。
脚本中的命令 b 告诉 sed 在此时结束脚本。
所以第一个 -e 命令告诉 sed 结束脚本并打印所有不在开头和结尾的行。
第二个 -e 命令告诉 sed 在找到带有 end.
的行时打印文件 file2.txt
第三个 -e 命令告诉 sed 删除(不打印)从开始到结束的行。