kennyg kennyg - 2 months ago 9
Perl Question

Fill file with missing lines perl

I have a file that contains the following:

value1;1;1
value2;2;2
value3;5;5
value4;7;7
value5;1;8
value6;3;10
value7;7;14


The first column contains a random value, the second column numbers 1 to 7 ordered, and the third column just consecutive numbers.
Is it possible, using perl, to fill this file in the following way:

value1;1;1
value2;2;2
null;3;3
null;4;4
value3;5;5
null;6;6
value4;7;7
value5;1;8
null;2;9
value6;3;10
null;4;11
null;5;12
null;6;13
value7;7;14


Thanks!

Answer

Here's a simple one-liner that does that:

perl -ple '($m,$n)=/;(\d+);(\d+)$/; while ($l<$n) {print "null;",++$p,";$l" if $l; $l++} $l=$n+1; $p=$m' input

It uses a variable ($l) to remember the last value of the last column and if there are gaps it fills them before outputting each line.

Output:

value1;1;1
value2;2;2
null;3;3
null;4;4
value3;5;5
null;6;6
value4;7;7
value5;1;8
null;2;9
value6;3;10
null;4;11
null;5;12
null;6;13
value7;7;14