Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove new line if next line does not begin with a number

Tags:

file

sed

I have a file that is like

    1 test
    test

How can I remove the new line from the so the final output becomes:

1 test test

I already tried some sed but I could not het it to work.

like image 441
justahuman Avatar asked Feb 24 '23 16:02

justahuman


2 Answers

This should do the trick:

sed -n '$!{ 1{x;d}; H}; ${ H;x;s|\n\([^0-9]\)| \1|g;p}' inputfile

Input:

1 test1
test1
2 test2
test2
test2
3 test3
4 test4

Output:

1 test1 test1
2 test2 test2 test2
3 test3
4 test4
like image 192
ssapkota Avatar answered Mar 24 '23 10:03

ssapkota


You can be a bit smarter and print a new line before the line if it starts with a digit (except for the first line);

awk 'BEGIN{ORS="";} NR==1 { print; next; } /^[[:digit:]]/ { print "\n"; print; next; } { print; }'

The awk script:

BEGIN { ORS=""; }                            # default: no newline between output records
NR==1 { print; next; }                       # first line: print
/^[[:digit:]]/ { print "\n"; print; next; }  # if starts with a digit: print newline before
{print;}                                     # other lines (next; has not been called yet)
like image 39
Benoit Avatar answered Mar 24 '23 09:03

Benoit