Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mask output card number with ****

Tags:

bash

sed

I have a task to mask the first 12 digits of each credit card number with an asterisk (*) given an input file, and print the masked number to an output file.

Example card numbers:

1111-2222-3333-4444
4444-3333-2222-1111
1234-5678-9101-1171
1234 5678 9101 1121
7347_9834_7598_2834
8973#9858#3475#8734
2356`7843`0527`5340
8734=7583=4895=7007
8763+2430+6257_9406

Everything should be done in a shell script.

My solution is:

#!/bin/bash

file='cards.txt'
while read data; do
echo $data | sed -r 's/[[:digit:]]{4}/****/;s/[[:digit:]]{4}/****/;s/[[:digit:]]{4}/****/;s/[^0-9,*]+/ /g'
done < $file > cards-masked.txt

Any better ideas on how to use sed in this task?

like image 656
isvalx Avatar asked Dec 14 '22 06:12

isvalx


1 Answers

Looking at the example data, it seems you have always 4 digits separated by a character other than a digit.

If you are interested in using an awk solution as well, you can replace all chars other than a digit with a space first.

Then replace all chars in the first 3 columns with *

awk '{gsub(/[^0-9]+/, " ");for (i=1;i<4;i++) gsub(/[0-9]/,"*",$i)}1' cards.txt > cards-masked.txt

A bit more readable version with a short explanation

awk '{
  gsub(/[^0-9]+/, " ")                    # Replace all chars other than 0-9 with a space
  for (i=1;i<4;i++) gsub(/[0-9]/,"*",$i)  # Loop the first 3 columns, replace all digits with *
}1' cards.txt > cards-masked.txt          # The 1 evaluates to true, printing the whole line

Output

**** **** **** 4444
**** **** **** 1111
**** **** **** 1171
**** **** **** 1121
**** **** **** 2834
**** **** **** 8734
**** **** **** 5340
**** **** **** 7007
**** **** **** 9406
like image 184
The fourth bird Avatar answered Dec 25 '22 23:12

The fourth bird