String 如何使用sed/awk连接连续的非空行?

String 如何使用sed/awk连接连续的非空行?,string,awk,sed,concatenation,lines,String,Awk,Sed,Concatenation,Lines,如何使用sed或awk将连续的非空行连接到单个行中? 举了一个例子说明我正在努力做什么 输入: aaa ff gg bbb eee eee ss gg dd aaa ff gg bbb eee eee ss gg dd aaa ff gg bbb eee eee ss gg dd 皈依 aaa ff gg bbb eee eee ss gg dd aaa ff gg bbb eee eee ss gg dd aaa ff gg bbb eee eee ss gg dd @肖恩:@试试

如何使用sed或awk将连续的非空行连接到单个行中? 举了一个例子说明我正在努力做什么

输入:

aaa ff gg
bbb eee eee
ss gg dd

aaa ff gg
bbb eee eee
ss gg dd

aaa ff gg
bbb eee eee
ss gg dd
皈依

aaa ff gg bbb eee eee ss gg dd

aaa ff gg bbb eee eee ss gg dd

aaa ff gg bbb eee eee ss gg dd
@肖恩:@试试看:

awk '{ORS=/^$/?RS RS:FS} {$1=$1} 1;END{print RS}'  Input_file
编辑:现在也添加解释

awk '{ 
ORS=               ##### Setting Output field separator here.
/^$/               ##### Checking the condition if a line starts from null.
?                  ##### ? means if above condition is TRUE then run following action.
RS RS              ##### set ORS as RS RS means set it to 2 new lines, default value of RS will be new line.
:                  ##### : is a conditional operator which will execute the action following it when condition is FALSE.
FS}                ##### Set ORS to FS, which is field separator and it's default value is space.
{$1=$1}            ##### Re-setting the first field again of line to reflect the new value of ORS.
1;                 ##### making the condition as TRUE and not mentioning the action, so by default print will happen of current line.
END
{print RS}         ##### printing the RS value at last which is new line.
'  Input_file      ##### Mentioning the Input_file here.

如果
perl
正常:

$ perl -00 -pe 's/\n(?!$)/ /g' ip.txt
aaa ff gg bbb eee eee ss gg dd

aaa ff gg bbb eee eee ss gg dd

aaa ff gg bbb eee eee ss gg dd
  • -00
    以段落模式读取输入
    • 有关更多信息和
      -pe
      选项,请参阅
    • 使用
      perl-i-00-pe
      进行就地编辑
  • s/\n(?!$)//g
    将除空行中的换行符外的所有换行符替换为空格

不确定您是否真的希望在每个数据行之间都有一个空行,因此以下是两个:

$ awk -v RS= '{$1=$1}1' file
aaa ff gg bbb eee eee ss gg dd
aaa ff gg bbb eee eee ss gg dd
aaa ff gg bbb eee eee ss gg dd

$ awk -v RS= -v ORS='\n\n' '{$1=$1}1' file
aaa ff gg bbb eee eee ss gg dd

aaa ff gg bbb eee eee ss gg dd

aaa ff gg bbb eee eee ss gg dd

更具可读性的示例,不太像Perl:

awk '{ if ($0 == "") { print line "\n"; line = "" } else line = line $0 } END { if (line) print line }' file
这可能适用于您(GNU-sed):

除非附加的最后一行为空,否则将换行符替换为空格并重复。否则打印并重复

如果要删除空行,则:

sed ':a;N;/\n$/!s/\n/ /;ta;P;d' file

有人能告诉我投票的原因吗?将尝试改进编解码器,但答案通常是肯定的。即使是像中这样的一点点解释也会有很大帮助。@Aurora0001:完成,现在添加解释。
sed ':a;N;/\n$/!s/\n/ /;ta;P;d' file