$ cat mask_digs.pl #!/usr/bin/perl use strict; use warnings; while () { print $_; # Chop up the string my @list = map { defined($_) ? $_ : '' } split /(\d)/; # Replace all digits with X, other than first six and last 4. s/\d/X/ for @list[12 .. $#list-8]; # Join it back together print join("", @list), "\n"; } __DATA__ 5432 1234 12346 6694 a16-994-332-1234-16 123321123333333