假设我有两个文件。如何执行以下操作,即将一个文件中的标记部分复制到另一个文件的某个位置?某些 sed 命令可以完成这项工作吗?最实用的方法是什么?
文件#1:
This paragraph does not belong to the poem.
{ begin passage #1 }
When from a place he run away,
He never at the place did stay;
And while he run, as I am told,
He never stood still for young or old.
He often squeaked, and sometimes violent,
And when he squeaked he never was silent.
Though never instructed by a cat,
He knew a mouse was not a rat.
{ end passage #1 }
This as well does not.
文件#2:
There was a little guinea pig,
Who being little, was not big;
He always walked upon his feet,
And never fasted when he eat.
{ input passage #1 file #1 }
One day, as I am certified,
He took a whim, and fairly died;
And as I am told by men of sense,
He never has been living since.
我希望将文件 #1 中的段落插入到文件 #2 的给定标记处。感谢帮助和想法!
最佳答案
当您问“最实用的方法是什么”时,我的回答是使用 shell 脚本将 sed
和 awk
混合在一起,将整个过程粘合在一起。
尝试仅使用 sed
来解决这个问题可能是可能的,但不值得花时间去弄清楚。
几乎肯定可以进行进一步的优化,但我尝试编写您可以理解的代码,而不是一行代码;-)。
#!/bin/ksh
sed -n '/^{ begin passage/,/^{ end passage /p' file_1 | sed '/^{/d' > /tmp/$$.segment
awk -v segFile="/tmp/$$.segment" '{
if ($0 ~ /^{ input passage/) {
while (getline < segFile > 0 ) {
print $0
}
next
}
else {
print $0
}
}' file_2
rm /tmp/$$.segment
输出
There was a little guinea pig,
Who being little, was not big;
He always walked upon his feet,
And never fasted when he eat.
When from a place he run away,
He never at the place did stay;
And while he run, as I am told,
He never stood still for young or old.
He often squeaked, and sometimes violent,
And when he squeaked he never was silent.
Though never instructed by a cat,
He knew a mouse was not a rat.
One day, as I am certified,
He took a whim, and fairly died;
And as I am told by men of sense,
He never has been living since.
如果需要,您可以将 #!/bin/ksh
更改为 #!/bin/bash
。
您可以对输出进行后过滤以消除重复的空白行,但尚不清楚您的最终需求是什么。
IHTH
关于text - 将分组的文本行复制并粘贴到另一个文件中的优雅方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33964667/