如何合并具有某些内容的文本并保留空行

How to merge text having some content and leave blank lines

我在 Ubuntu 上有一个地址 txt 文件。像下面这样的东西 -

Name
Address1
Address2
Address3

Name2
Address12
Address22
Address32

如何合并内容 -

Name Address1 Address2 Address3
Name2 Address12 Address22 Address32

实际上,地址是一个接一个地写入文件的——就像上面提到的那样。新地址由新行或空行分隔。现在我想将每个地址行合并为一行 - 对所有地址重复如此

awk -v ORS=" " '{print}/^$/{printf("\n")}END{printf("\n")}' File

设置输出记录分隔符(ORS)为space,打印每一行。每当遇到空行时,打印 newline ("\n")。在 END 块中打印 "\n" 以获得所需的输出。希望这就是你想要的。

样本:

sdlcb@Goofy-Gen:~/AMD$ cat File
Name
Address1
Address2
Address3

Name2
Address12
Address22
Address32

Name2
Address12
Address22
Address32
sdlcb@Goofy-Gen:~/AMD$ awk -v ORS=" " '{print}/^$/{printf("\n")}END{printf("\n")}' File
Name Address1 Address2 Address3
Name2 Address12 Address22 Address32
Name2 Address12 Address22 Address32

RS设置为空字符串将使用一个或多个空行作为记录分隔符。

$ cat addr.txt
Name
Address1
Address2
Address3

Name2
Address12
Address22
Address32




Name3
Address13
Address23
Address33

$ awk 'BEGIN { RS="" } { gsub("\n"," ") }1' addr.txt
Name Address1 Address2 Address3
Name2 Address12 Address22 Address32
Name3 Address13 Address23 Address33

来自 awk 用户指南:

RS == ""

Records are separated by runs of blank lines. When FS is a single character, then the newline character always serves as a field separator, in addition to whatever value FS may have. Leading and trailing newlines in a file are ignored.

这是一个awk

awk -v RS= '{=}1' file
Name Address1 Address2 Address3
Name2 Address12 Address22 Address32
Name3 Address13 Address23 Address33

通过设置 RS 使 awk 使用数据块作为记录。
{=}1重建线。

如果字段以 0 开头(不太健壮),则会失败:

awk -v RS= '=' file