打印包含图案的行,连接下一行,直到找到具有图案的下一行

时间:2019-06-28 06:05:38

标签: awk sed

数据:

<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.

3 个答案:

答案 0 :(得分:0)

请您尝试以下。

awk '
/^<START>/{
  if(value){
     print value
     value=""
  }
  value=$0
  next
}
{
  value=(value?value OFS:"")$0
}
END{
  if(value){
     print value
  }
}'   Input_file

答案 1 :(得分:0)

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

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

关闭自动打印-n

如果一行不包含START,则将其附加到保留空间,如果不是最后一行,则将其从当前循环中删除。

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

通过在累积行之后交换到容纳空间,当前行将成为新容纳空间的第一行。另外,该解决方案用空格替换换行符,如果这不是期望的结果,则可以使用以下命令删除换行符:

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

答案 2 :(得分:0)

$ awk '{printf "%s%s", (/^<START>/ ? sep : ""), $0; sep=ORS} 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.

,或者您愿意(例如,如果需要在打印之前建立完整记录以进行处理):

$ awk '/^<START>/{if (NR>1) print rec; rec=""} {rec = rec $0} END{print rec}' 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.

它们都可以在每个UNIX机器上的任何shell中的任何awk中使用。