Awk 连接两个模式

Awk 连接两个模式,awk,sed,Awk,Sed,我一直在寻找答案,但没有找到有效的方法。这就是我正在努力实现的目标。在一个文件中,我有以特定模式开头的行,有时它们之间有一行,有时没有。我正在尝试将图案之间的线条连接到第一条图案线条。示例如下: 电流输出: Name: Doe John Some Random String Mailing Address: 1234 Street Any Town, USA 注意:“somerandomstring”行有时不存在,因此不需要联接 期望输出: Name: Doe John Some

我一直在寻找答案,但没有找到有效的方法。这就是我正在努力实现的目标。在一个文件中,我有以特定模式开头的行,有时它们之间有一行,有时没有。我正在尝试将图案之间的线条连接到第一条图案线条。示例如下:

电流输出:

Name: Doe John   
Some Random String  
Mailing Address: 1234 Street Any Town, USA  
注意:“somerandomstring”行有时不存在,因此不需要联接

期望输出:

Name: Doe John Some Random String  
Mailing Address: 1234 Street Any Town, USA    
我试过在网上找到的sed和awk答案,但我不知道该如何做。我的sed和awk技能在这一点上是非常基本的,所以即使在解释时,我也不太理解一些解决方案


感谢您提供的任何帮助或指向文档的一点,这些文档讲述了我正在尝试完成的工作。

您能否尝试使用GNU
awk
中显示的示例编写并测试以下内容

awk  '{printf("%s%s",FNR>1 && $0~/^Mailing/?ORS:OFS,$0)} END{print ""}' Input_file
或者,如果您只想为
Name
Mailing
这两个字符串添加新行,请尝试以下操作

awk  '
{
  printf("%s%s",FNR>1 && ($0~/^Mailing/ || $0 ~/Name:/)?ORS:OFS,$0)
}
END{
  print ""
}
' Input_file
说明:添加上述内容的详细说明

awk  '        ##Starting awk program from here.    
{
  printf("%s%s",FNR>1 && ($0~/^Mailing/ || $0 ~/Name:/)?ORS:OFS,$0)
              ##Using printf to print strings, 1st one is either newline or space, which is based on
              ##condition if line is greater than 1 OR line is either starts with Mailing or has Name
              ##Then print ORS(newline) or print OFS(space). For 2nd string print current line.
}
END{          ##Starting END block of this program from here.
  print ""    ##Printing new line here.
}
' Input_file  ##Mentioning Input_file name here.

定义特定模式的另一个awk:

在稍微修改的数据上输出(额外的空间来自您的数据,未对其进行修剪):


一个
GNU-sed
解决方案怎么样:

sed '
/^Name:/{                               ;# if the line starts with "Name:" enter the block
N                                       ;# read the next line and append to the pattern space
:l1                                     ;# define a label "l1"
/\nMailing Address:/! {N; s/\n//; b l1} ;# if the next line does not start with "Mailing Address:"
                                        ;# then append next line, remove newline and goto label "l1"
}' file
这可能适用于您(GNU-sed):


如果一行包含
名称:
请继续在换行符的任何一侧添加行并用空格替换空格,直到文件结尾或包含
邮寄地址:
的行很好,您已经提到您在论坛中进行了查看,请在您的问题中也进行这些努力/代码,这里没有对错之分,因为我们都是为了学习,我们强烈鼓励大家在问题上多加努力,所以,干杯。你的文件总是只有两三行?答案很好,有全面的解释!
Name: Doe John   Some Random String  
Mailing Address: 1234 Street Any Town, USA  Using: but not specific pattern
sed '
/^Name:/{                               ;# if the line starts with "Name:" enter the block
N                                       ;# read the next line and append to the pattern space
:l1                                     ;# define a label "l1"
/\nMailing Address:/! {N; s/\n//; b l1} ;# if the next line does not start with "Mailing Address:"
                                        ;# then append next line, remove newline and goto label "l1"
}' file
sed '/Name:/{:a;N;/Mailing Address:/!s/\s*\n\s*/ /;$!ta}' file