将分组的文本行复制并粘贴到另一个文件中的优雅方法

时间:2015-11-27 20:55:28

标签: text command-line sed copy-paste

假设我有两个文件。如何执行以下操作,即将标记的部分从一个文件复制到另一个文件的某个位置?一些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中。感谢帮助和想法!

2 个答案:

答案 0 :(得分:2)

正如您所说的那样,#34;最实用的方式是什么?#我使用shell脚本将sedawk混合在一起,将整个事物粘合在一起。

尝试仅使用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

答案 1 :(得分:1)

这可能适合你(GNU sed):

sed -n '/{ begin/,/{ end/!b;//!p' file1 | sed -e '/{ input/r /dev/stdin' -e '//d' file2 

过滤来自file1的行并将它们插入到file2中。第一个sed命令的stdout成为第二个sed命令的stdin文件。第二个sed调用需要两个sed命令,因为r命令必须以换行符(或新的-e sed命令)结束。第二个sed命令删除插入第一个文件中的行的行。