0

I have data file looks like:

1
2 4 5 6 7 19
20
22
24 26 27 
29 30 31 32 34 40 50 56 58
234 235 270 500
1234 1235 1236 1237
2300

I want to split those rows with more than 4 column to smaller rows with maximum 4 columns within each row. therefore the output should be:

 1
 2 4 5 6 
 7 19
 20
 22
 24 26 27 
 29 30 31 32
 34 40 50 56
 58
 234 235 270 500
 1234 1235 1236 1237
 2300

Any suggestion please? Please consider that my real data file is huge.

2 Answers 2

2

With awk:

awk '{ if(NF>4) for(i=5; i<=NF; i+=4) $i = "\n" $i } 1' file

With sed:

sed 's/ /\n/4;T;P;D' file

With perl:

perl -lpe '$c = 0; s/ /++$c % 4 ? " " : "\n"/goe' file

Output:

1
2 4 5 6 
7 19
20
22
24 26 27 
29 30 31 32 
34 40 50 56 
58
234 235 270 500
1234 1235 1236 1237
2300
1

The easiest approach would be a late merge or zipper method. Assume last character of each line is white space. First split your file into two, with respect to the columns you want to cut.

cut -d' ' -f1-4 file > file1
cut -d' ' -f5- file > file2

Secondly merge the files via late merge and delete empty lines.

paste -d'\n' file1 file2 | sed '/^$/d'

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .