2

I have some text files where each file will have some information as below

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

and the pattern repeats

I want the text to be arranged as follows:

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

That means I want to merge all the lines between two matching patterns( with spaces between them)

I want every line to start with the numbers as the pattern. The numbers always has a decimal point with two digits after the decimal point. The number of lines between a pattern and the next pattern varies (There can be one or more lines or no lines at all).

Could some one help me do this using shell scripting preferably using awk?

glenn jackman
  • 238,783
  • 38
  • 220
  • 352
user1540393
  • 69
  • 1
  • 8

3 Answers3

7

It sounds like you need something like this:

awk '
{ printf "%s%s", ($1 ~ /\.[[:digit:]][[:digit:]]/ ? rs : FS), $0; rs=RS }
END { print "" }
' file
Ed Morton
  • 188,023
  • 17
  • 78
  • 185
  • I have same problem. If we have this 2016-03-19 instead of "235.91 245.67 B" and same across the file in every line. What would be the pattern? Please help – Deepak Kumar Mar 19 '16 at 09:54
  • got the answer . http://stackoverflow.com/questions/36100615/merge-multiple-lines-between-same-pattern-into-a-single-line-using-awk-sed/36100673?noredirect=1#comment59844985_36100673 – Deepak Kumar Mar 20 '16 at 02:00
1

I don't know about awk, but sed works too:

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

Explanation of the scary thing before sed is here: How can I replace a newline (\n) using sed?

Community
  • 1
  • 1
snetch
  • 458
  • 4
  • 18
1

@EdMorton's answer is niftier but this also works.

$1 ~ /^[[:digit:]]+\.[[:digit:]][[:digit:]]$/ { if (NR-1) {print ""} printf "%s", $0; next }
{printf " %s", $0}
END { print ""}
Etan Reisner
  • 77,877
  • 8
  • 106
  • 148