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

时间:2017-04-07 14:27:29

标签: 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

5 个答案:

答案 0 :(得分:2)

不确定您是否真的想要在每条数据线之间留一个空行,所以这两者都是:

$ 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

答案 1 :(得分:1)

@Schon:@try:

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.

答案 2 :(得分:1)

如果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

答案 3 :(得分:1)

一个更易读的例子,更像Perl:

awk '{ if ($0 == "") { print line "\n"; line = "" } else line = line $0 } END { if (line) print line }' file

答案 4 :(得分:1)

这可能适合你(GNU sed):

div

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

如果要删除空行,则:

display: none;