用多行文本替换单行

SSS*_*SSS 8 linux shell

在Linux中,我可以用什么命令用新的多行替换单行文本?我想在一行上查找关键字并删除此行并将其替换为多个新行.因此,在下面显示的文本中,我想搜索包含"keyword"的行,并用3行新文本替换整行,如图所示.

例如,替换包含关键字的行,

This is Line 1
This is Line 2 that has keyword
This is Line 3
Run Code Online (Sandbox Code Playgroud)

改为:

This is Line 1
Inserted is new first line
Inserted is new second line
Inserted is new third line
This is Line 3
Run Code Online (Sandbox Code Playgroud)

kev*_*kev 12

$ sed '/keyword/c\
> Inserted is new first line\
> Inserted is new second line\
> Inserted is new third line' input.txt

This is Line 1
Inserted is new first line
Inserted is new second line
Inserted is new third line
This is Line 3
Run Code Online (Sandbox Code Playgroud)

$并且>是bash提示

  • 你如何计时,以便在一个小时过去之后没有人回答这个问题,你设法提前一分钟提交答案! (2认同)
  • 纯属巧合 (2认同)

Jon*_*ler 8

创建一个文件script.sed,包含:

/keyword/{i\
Inserted is new first line\
Inserted is new second line\
Inserted is new third line
d
}
Run Code Online (Sandbox Code Playgroud)

将其应用于您的数据:

sed -f script.sed your_data
Run Code Online (Sandbox Code Playgroud)

关于如何操作有很多变化,使用ca命令而不是i和/或d,但这是相当干净的.它找到关键字,插入三行数据,然后删除包含关键字的行.(该c命令完成所有操作,但我不记得它存在,并且a命令附加文本,并且i在此上下文中基本上是同义词.)