如何使用awk将两个模式之间的未知数量的多行合并为一行

时间:2014-01-13 19:15:23

标签: shell awk grep

我有一些文本文件,其中每个文件都有一些信息,如下所示

235.91 245.67 B: some information here
246.79 246.99 A: some other information here,
more information here,
and may be here
247.45 248.99 A: some other text here,
some more here
249.98 ---- 

并且模式重复

我希望文字排列如下:

235.91 245.67 B: some information here
246.79 246.99 A: some other information here, more information here, and may be here
247.45 248.99 A: some other text here. some more here
249.98 -----

这意味着我想合并两个匹配模式之间的所有行(它们之间有空格)

我希望每一行都以数字作为模式开始。数字始终有一个小数点,小数点后有两位数。图案与下一个图案之间的线数不同(可以有一条或多条线或根本没有线)。

是否有人可以帮助我使用shell脚本执行此操作,最好使用awk?

3 个答案:

答案 0 :(得分:7)

听起来你需要这样的东西:

awk '
{ printf "%s%s", ($1 ~ /\.[[:digit:]][[:digit:]]/ ? rs : FS), $0; rs=RS }
END { print "" }
' file

答案 1 :(得分:1)

我不知道awk,但sed也有效:

grep -v '^$' | sed ':a;N;$!ba;s/\n\([^0-9]\)/ \1/g'

sed之前可怕的事情的解释是: How can I replace a newline (\n) using sed?

答案 2 :(得分:1)

@ EdMorton的回答是琐碎的,但这也有效。

$1 ~ /^[[:digit:]]+\.[[:digit:]][[:digit:]]$/ { if (NR-1) {print ""} printf "%s", $0; next }
{printf " %s", $0}
END { print ""}
相关问题