sedreplacepositioncredit-cardanonymize

Find credit card numbers and replace characters at set positions


I have a file that contains credit card numbers (16 characters), I want to find them and replace everything with "X" apart from the first 6 and last 4 numbers.

sed -i 's/\([345]\{1\}[0-9]\{3\}\|6011\)\{1\}[ -]\?[0-9]\{4\}[ -]\?[0-9]\{2\}[-]\?[0-9]\{2\}[ -]\?[0-9]\{1,4\}/\XXXXXX/g' foobar.csv

Will easily find all credit cards contained in the file and replace them with "XXXX"

But I want to find the credit cards and replace only characters 7-12 of the string with "X", so the file will contain credits which are masked like this 123456XXXXXX7890.

Sample input line:

jam peanut boat handbag on the shore in Tuesday 4548640040302006 in the morning jimmy

Sample output line:

jam peanut boat handbag on the shore in Tuesday 454864XXXXXX2006 in the morning jimmy

Solution

  • Try this with GNU sed to anonymize credit card numbers:

    sed -i 's/\(\([345]\{1\}[0-9]\{3\}\|6011\)\{1\}[ -]\?[0-9]\{2\}\)[0-9]\{2\}[ -]\?[0-9]\{2\}[-]\?[0-9]\{2\}[ -]\?\([0-9]\{1,4\}\)/\1XXXXXX\3/g' file
    

    Input:

    jam peanut boat handbag on the shore in Tuesday 4548640040302006 in the morning jimmy
    jam peanut boat handbag on the shore in Tuesday 454864XXXXXX2006 in the morning jimmy
    

    Output to file:

    jam peanut boat handbag on the shore in Tuesday 454864XXXXXX2006 in the morning jimmy
    jam peanut boat handbag on the shore in Tuesday 454864XXXXXX2006 in the morning jimmy