首页 > 解决方案 > 打印包含模式的行,连接下一行直到找到模式的下一行

问题描述

数据:

<START>|3|This is the first step.
This describes the first step.
There are many first steps to be followed and it can go on for multiple lines as you can see.
<START>|7|This is the eighth step.
This describes what you need to know and practice.
There are many such steps to be followed and it can go on for several lines as you can see.
<START>|14|This is the eleventh step.
This describes how to write a code in awk.
There are many such steps to be followed and it can go on for several lines as you can see.

请帮忙。

尝试了以下,但它没有打印包含字符串的行。即使修改后,它仍然不会将第一行与字符串连接到下一行没有字符串。新行仍然存在。

awk '/START/{if (NR!=1)print "";next}{printf $0}END{print "";}' file

需要输出:

<START>|3|This is the first step.This describes the first step.There are many first steps to be followed and it can go on for multiple lines as you can see.
<START>|7|This is the eighth step.This describes what you need to know and practice.There are many such steps to be followed and it can go on for several lines as you can see.
<START>|14|This is the eleventh step.This describes how to write a code in awk.There are many such steps to be followed and it can go on for several lines as you can see.

标签: awksed

解决方案


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

 sed -n '/START/!{H;$!b};x;s/\n/ /gp' file

关闭自动打印-n

如果一行不包含 START,则将其附加到保持空间,如果它不是文件的最后一行,则退出当前循环。

否则,交换到保留空间并用空格替换所有换行符,如果成功则打印结果。

NB 通过在行累积后交换到保持空间,当前行成为新保持空间的第一行。此外,该解决方案用空格替换换行符,如果这不是所需的结果,则可以使用以下方法删除换行符:

 sed -n '/START/!{H;$!b};x;s/\n//gp' file

推荐阅读