-1

我一直在寻找这个问题的答案,但没有找到有效的方法。这就是我想要完成的。在一个文件中,我有以特定模式开头的行,有时它们之间有一条线,而其他时候则没有。我正在尝试将模式之间的线连接到第一条模式线。下面的例子:

电流输出:

Name: Doe John   
Some Random String  
Mailing Address: 1234 Street Any Town, USA  

注意:“一些随机字符串”行有时不存在,因此不需要连接

期望的输出:

Name: Doe John Some Random String  
Mailing Address: 1234 Street Any Town, USA    

我已经尝试过在网上找到的 sed 和 awk 答案,但无法解决如何使这项工作。在这一点上,我的 sed 和 awk 技能非常基础,因此即使在解释时我也不太了解某些解决方案。

感谢您提供任何帮助或指向有关我要完成的工作的文档。

4

4 回答 4

3

您能否尝试在 GNU 中使用显示的示例进行跟踪、编写和测试awk

awk  '{printf("%s%s",FNR>1 && $0~/^Mailing/?ORS:OFS,$0)} END{print ""}' Input_file

或者,如果您只想为两个字符串添加新行,请尝试以下操作NameMailing

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.
于 2020-11-15T06:07:51.207 回答
1

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

$ awk '
BEGIN {
    p["Name"]              # define the specific patters that start the record
    p["Mailing Address"]
}
{
    printf "%s%s",(split($0,t,":")>1&&(t[1] in p)&&NR>1?ORS:""),$0
}
END {
    print ""               # conditional operator controls the ORS so needed here 
}' file

稍微修改数据的输出(额外的空间来自您的数据,没有修剪它们):

Name: Doe John   Some Random String  
Mailing Address: 1234 Street Any Town, USA  Using: but not specific pattern
于 2020-11-15T07:10:55.753 回答
1

怎么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
于 2020-11-15T07:56:19.817 回答
0

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

sed '/Name:/{:a;N;/Mailing Address:/!s/\s*\n\s*/ /;$!ta}' file

如果一行包含Name:继续追加行并用空格替换换行符两侧的空白,直到文件末尾或包含Mailing Address:.

于 2020-11-15T14:42:34.613 回答