如何复制包含特定单词和多个连续行的行(例如:使用awk或sed)?

如何复制包含特定单词和多个连续行的行(例如:使用awk或sed)?,awk,sed,Awk,Sed,我正在尝试复制和操作文件的特定行,从以下示例开始。yaml: game: name: test ability: 1 name: other ability: 2 我想复制行name:test和ability:1,但不复制其他内容。 我不想使用行号来选择写行,因为大小和内容各不相同 结果应该是: game: name: test ability: 1 name: test ability: 1 name: other ability: 2 game

我正在尝试复制和操作文件的特定行,从以下示例开始。yaml:

game:
  name: test
  ability: 1
  name: other
  ability: 2
我想复制行
name:test
ability:1
,但不复制其他内容。 我不想使用行号来选择写行,因为大小和内容各不相同

结果应该是:

game: 
  name: test
  ability: 1
  name: test
  ability: 1
  name: other 
  ability: 2
game: 
  name: test
  ability: 1
  name: test
  ability: 1
我设法用以下方法解决了这个问题:

awk '
/name: test/ {f=1}
/name: other/{
  f=0;
  for(i=1;i<=c;i++) print a[i]
}
f{ print; a[++c]=$0 }
!f{ print}
' example.yaml
应该是:

game: 
  name: test
  ability: 1
  name: test
  ability: 1
  name: other 
  ability: 2
game: 
  name: test
  ability: 1
  name: test
  ability: 1
如何创建一个更通用的解决方案,而不使用我试图复制的模式


感谢sed中的简单明了:

sed '/name: test/{N;p;}' filename
粗略地翻译,这表示“如果这一行包含
name:test
,那么也读入下一行,然后额外打印出来”。

这可能对您有用(GNU-sed):

sed'/\Awk备选方案:

awk '/name: test/ { line=$0 } /ability/ && line!="" { $0=$0"\n"line"\n"$0;line=""}1' file

如果找到行“name:test”,则将变量行设置为等于读取行($0),然后当我们发现行能力和行不等于“”(名称为test)时,将读取行$0设置为等于现有行,然后使用回车符、行变量(name:test),然后再次设置现有行。将行变量重置为空。使用速记1打印该行。

您是说
要复制行名称:test and ability:play,但除此之外没有其他内容
但您的预期输出中没有
ability:play
行?你能在你的问题中澄清一下吗?使用一种带有yaml库的编程语言,就像PythonThanks一样!这一个似乎是最容易理解和工作良好。