kirkbrown has asked for the wisdom of the Perl Monks concerning the following question:

Using the Unix command line, how would I trim varying length phone numbers (i.e. some 10, 13, or 7 digits) to only the first seven digits from the right and place and asterisk in front?

Replies are listed 'Best First'.
Re: Trim Phone Numbers
by BrowserUk (Patriarch) on Dec 15, 2009 at 04:38 UTC
    c:\test>perl -nlE"say '*' . substr $_, -7" 1235551234 *5551234 0011235551234 *5551234 5551234 *5551234

    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.
Re: Trim Phone Numbers
by GrandFather (Saint) on Dec 15, 2009 at 03:34 UTC
    perl -e 'print qq!$_\n! for grep {length} map {s/.*(\d{7})/*$1/ ? $_ : + q!!} @ARGV;' 1234567890 1234567 1234567890123 wibble 123

    Prints:

    *4567890 *1234567 *7890123

    True laziness is hard work
Re: Trim Phone Numbers
by bv (Friar) on Dec 15, 2009 at 04:20 UTC
    perl -lnpe 's/.*(?=\d{3}-?\d{4}$)/*/'

    or another interpretation of your question:

    perl -lnpe 's/(\d\d-?)(\d{3}-?)(?=\d{3}-?\d{4}$)/$1=~tr!0-9!*!;$2=~tr!0-9!*!;$1.$2/e

    @_=qw; Just another Perl hacker,; ;$_=q=print "@_"= and eval;
Re: Trim Phone Numbers
by planetscape (Chancellor) on Dec 15, 2009 at 23:36 UTC
Re: Trim Phone Numbers
by afoken (Chancellor) on Dec 16, 2009 at 20:42 UTC

    Just a small note: Phone numbers are very different from region to region, and simply cutting off some digits here and there will likely damage them. The US notation 555-1234-567 looks completely strange to someone living in Europe, and vanity numbers like 555-SHOE-SHOP were nearly unknown until a few years ago. Not that we europeans would share a common notation. The german standards recommend to have pairs of digits, right-aligned, with private extensions indicated by a dash, and the long distance prefix either in brackets or with a slash: 0 12 34 / 5 67 89-1 23. For regional phone numbers, the prefix is usually omitted. Other countries group three digits, or don't group at all, some have no concept of long-distance calls. Various characters are used to separate digit groups, like white space, dots, slashes, dashes, and brackets. So, any random group of up to 13(? - ITU limit) digits with optional interpunctation could be a valid phone number. When it comes to vanity numbers, things get even worse.

    Several libraries that pretend to be able to handle phone numbers can in fact handle only US phone numbers and fail miserably when they are confronted with non-US phone numbers.

    Alexander

    --
    Today I will gladly share my knowledge and experience, for there are no sweeter words than "I told you so". ;-)