$/ = \4096; my $flag = 0; while (<>) { if ($flag) { # ended previous chunk in mid-substitution s/(^[^\x00]*(\z|\x00))/"\x00" x length $1/ge; } s/(1379[^\x00]*(\z|\x00))/"\x00" x length $1/ge; $flag = length $2 ? 0 : 1; # this could be readily golfed, I realize }