$ 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 #### $ perl mask_digs.pl 5432 1234 12346 6694 5432 12XX XXXXX 6694 a16-994-332-1234-16 a16-994-3XX-XX34-16 123321123333333 123321XXXXX3333