Good day. Tell me how you can correctly add the prefix to a certain number of lines. There is a file containing ~ 100k lines. With the structure of the form:

AAA:BBB:CCC AAA:BBB:CCC AAA:BBB:CCC $$ AAA:BBB:CCC AAA:BBB:CCC AAA:BBB:CCC $$ AAA:BBB:CCC AAA:BBB:CCC AAA:BBB:CCC $$ AAA:BBB:CCC AAA:BBB:CCC AAA:BBB:CCC 

I need to add the first 3 lines to the prefix 001: from 3 to 6, for example 007: from 6 to 9 :010 To get a file with the structure:

  001:AAA:BBB:CCC 001:AAA:BBB:CCC 001:AAA:BBB:CCC $$ 007:AAA:BBB:CCC 007:AAA:BBB:CCC 007:AAA:BBB:CCC $$ 010:AAA:BBB:CCC 010:AAA:BBB:CCC 010:AAA:BBB:CCC 

For one line I use approximately the following code:

  while(<IN>) { if ($. % 3 == 1){ my $line = $_; print OUT "002:".$line; } } close IN; close OUT; 

How does it scale to use the counter? Maybe there is a possibility in Perl to specify the gap?

  • "I need to add the first 3 lines to the prefix 001 :, from 3 to 6, for example 007: from 6 to 9: 010" in your example, from 4 to 6, the prefix 007, and 010 from 7 to 9. In general, what principle lines should be numbered, i.e. What is the number from 10 to 12? - edem
  • By the fact that you led, you need to add numbers to all strings except $$ . while meeting $$ you need to switch the current number to the next one. - Mike
  • @Mike That's right But I don’t quite understand how to implement this, so I stopped at the line number, since the number of lines in the range is known. - Evgeniy A
  • @edem The number can be any but in the format xxx :. - Evgeniy A
  • Well, you lead the current number to some variable. in a loop, if the string is $$ change the number and do nothing else. Otherwise (the string is not equal to $$ ) type the current number and string. If you do this by line numbers ... well, ok. but you still need to do the same thing just to check that the remainder of the division by 4 is not equal to any particular value, but it seems to me less convenient - Mike

1 answer 1

If I understand correctly what is required ...

 my $num=1; while(<IN>) { if(/\$\$/) { $num++; print OUT $_; } else { print OUT sprintf("%03d:%s",$num,$_); } } 

The $num number is currently displayed in strings. Operation ++ should be replaced with your way of getting the next number (for me it remains a mystery how the sequence 1, 7, 10 is obtained).

  • Such a sequence is taken from the database on request. - Evgeniy A
  • @EvgeniyA I think it will not be difficult to take the next number from the database in the place where I have ++ worth - Mike