shellsed

Sed command for masking credit card up to 12th digit


Given lines of credit card numbers, mask the first 12 digits of each credit card number with an asterisk (i.e., *) and print the masked card number on a new line. Each credit card number consists of four space-separated groups of four digits. For example, the credit card number 1234 5678 9101 1234 would be masked and printed as **** **** **** 1234.

How can we do it with the sed command, I'm not getting how to deal with spaces?

Sample Input

1234 5678 9101 1234  
2999 5178 9101 2234  

Sample Output

**** **** **** 1234
**** **** **** 2234

Solution

  • $ echo -e "hello
    1234 5678 9101 1234
    2999 5178 9101 2234
    something else" | sed -E "s/^[0-9]{4} [0-9]{4} [0-9]{4} ([0-9]{4})\b/**** **** **** \1/g"
    hello
    **** **** **** 1234
    **** **** **** 2234
    something else
    

    If you want to preserve the possibility of spaces ...

    $ echo -e "hello
    1234567891011234
    2999 5178 9101 2234
    something else" | sed -E "s/^[0-9]{4}(\s*)[0-9]{4}(\s*)[0-9]{4}(\s*)([0-9]{4})\b/****\1****\2****\3\4/g"
    hello
    ************1234
    **** **** **** 2234
    something else
    

    If you always want intermediate spaces in the output (even if not in the input), then replace \1, \2, and \3 with literal spaces.