>_ IzzyLab

Hands-on task

This task is step 29 of the course “Regular expressions”

Mask the cards

medium~7 min

In /root/payments.txt there are card numbers of the form 1234 5678 9012 3456. Mask all digits except the last four with the * character (for example **** **** **** 3456), writing the result to /root/masked.txt.

What you'll practise:
  • sed
  • regular expressions
  • capture groups
  • counting quantifier
  • data masking

Topic breakdown

Masking part of a string while keeping the rest is about capture groups in sed -E. To replace only the right piece, on the left you describe the structure of the WHOLE card (four groups of four digits), but wrap in parentheses only the fragment you want to keep — then return it to the replacement via the backreference \1. "Exactly four digits" is set with the counting quantifier {4}, not +, otherwise the pattern would catch groups of a different length. This is a general technique: capture what you keep, and simply rewrite what you mask as a literal.

What's checked

  1. Number masked
  2. First digits hidden

What it looks like