sed: conditional merge of multiple lines

与世无争的帅哥 提交于 2021-02-06 12:51:11

问题


I need to merge line of a file using sed based on a pattern. eg:

Input File:

X1 A B C D E F

\+ G H I J 1 

\+ LK T PP E OO 2

X2 DDF F Y 

\+ J W Q 

....

OutPut Expected:

X1 A B C D E F G H I J 1 LK T PP E OO 2

X2 DDF F Y J W Q 

..

I would like to equivalent of wat is possible in vi editor (:%s/\n+/ /g)

Searching the web I found a solution, which logically should have worked

sed -e '{:a; N; s/\n+/ /g; ta}' infile

But this command defies my understanding and logic, and has produced output

X1 A B C D E F

\+ G H I J 1 LK T PP E OO 2
X2 DDF F Y 

\+ J W Q 

....

Any ideas are welcome, & Thanks in advance

Srisurya


回答1:


This might work for you:

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

explanation:

  • :a is a loop placeholder
  • $!N means if not end-of-file append next line to current line.
  • s/\n+// means delete an end on line followed by a plus sign
  • ta means if last substitution worked branch to a loop placeholder
  • P print upto the first newline.
  • D delete upto and including the first newline.



回答2:


an alternative awk oneliner:

awk 'BEGIN{RS="  "}{gsub(/\n\n\+/,"")}1' yourFile



回答3:


potong's answer didn't work for me, but something similar works:

sed -e :a -e '$!N;s/\n+//;ta' -e 'P;D' file

Good sed docs here: http://sed.sourceforge.net/sedfaq3.html



来源:https://stackoverflow.com/questions/11290616/sed-conditional-merge-of-multiple-lines

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!