Sed regular expression to mask credit card

We need to disguise credit card numbers. Mask everything except the last 4 digits. I am trying to use SED. Since the length of a credit card number varies from 12 digits to 19, I am trying to write a regular expression. The resulting code will receive a string. If it contains a String of the form "CARD_NUMBER = 3737291039299199", it will mask the first 12 digits. The problem is how to write a regular expression for a credit card from 12 to 19 digits? If I write another expression for 12 digits, this will not work. This means that for a 12-digit credit card, the first 8 digits must be masked. for a 15-digit credit card, the first 11 digits must be masked.

 while read data; do
    var1=${#data}

    echo "Length is "$var1
    echo $data | sed -e "s/CARD_NUMBER=\[[[:digit:]]\{12}/CARD_NUMBER=\[\*\*\*\*\*\*\*\*/g"
    done
+3
source share
4 answers

What about

sed -e: a -e "s / [0-9] \ ([0-9] \ {4 \} \) / \ * \ 1 /; ta"

(This works in my shell, but you may need to add or remove a backslash or two.) The idea is to replace the digit, and then four digits with a star followed by four digits, and repeat this until until she has longer triggers.

+5
source

This is done in a single command sedwithout an inline newline:

sed -r 'h;s/.*([0-9]{4})/\1/;x;s/CARD_NUMBER=([0-9]*)([0-9]{4})/\1/;s/./*/g;G;s/\n//'

If yours seddoes not have -r:

sed 'h;s/.*\([0-9]\{4\}\)/\1/;x;s/CARD_NUMBER=\([0-9]*\)\([0-9]\{4\}\)/\1/;s/./*/g;G;s/\n//'

If yours sedis required -e:

sed -e 'h' -e 's/.*\([0-9]\{4\}\)/\1/' -e 'x' -e 's/CARD_NUMBER=\([0-9]*\)\([0-9]\{4\}\)/\1/' -e 's/./*/g' -e 'G' -e 's/\n//'

Here is what he does:

  • duplicate the number so that it is in the template space and holds the space
  • grab the last four digits
  • swap them on hold and the whole number in the space with the picture
  • grap ,
  • ( )
+4

,

var1="CARD_NUMBER=3737291039299199"
IFS="="
set -- $var1
cardnumber=$2
echo $cardnumber | awk 'BEGIN{OFS=FS=""}{for(i=1;i<=NF-4 ;i++){ $i="*"} }1'

$ ./shell.sh
************9199
+2

sed, , , , . sed, :

sed -e 's/CARD_NUMBER=\([0-9]*\)\([0-9]\{4\}\)/\1\
\2/' | sed -e '1s/./x/g ; N ; s/\n//'

.

sed , , ( sed). (1s/./x/g) (N ; s/\n//).

!

+1

Source: https://habr.com/ru/post/1732076/


All Articles