awk help to mask characters

Hi Guys, I'm not an expert so seeking advice on awk.
I need to mask numbers in a text field so that they show up as "*" except for the last 4.
Input:

Desired Output:

The part of the Code I am using gives me this Output

num=$(echo $num | awk 'BEGIN{FS=OFS=""}{for (i=1 ; i<=NF-4; i++) $i="*"} 1')

Here num is only the number that I am passing "(123) 456-7890 " or "34567 887272"

Thanks in advance for the help.

this is a bit convoluted - others might find a better, more generic approach - this is brute-force:

$ echo 'His phone number is (123) 456-7890 and account is 34567 887272. ' | \
   awk '
     BEGIN{m="************"} 
     {
      l=length($5);
      $5="(" substr(m,2,l-2) ")"

      l=index($6,"-")
      $6=substr(m,1,l-1) substr($6,l)

     l=length($(NF-1))
     $(NF-1)=substr(m,1,l)

     match($NF,".*[^0-9]")
     $NF=substr(m,1,RLENGTH-5) substr($NF,RLENGTH-4)
}
1'

produces:

His phone number is (***) ***-7890 and account is ***** **7272.
1 Like

My idea would be to condition the assignment of an asterisk to $i only when it is a digit, i.e.:

if($i~="[0-9]")$i="*"

Hope it helps

It's slightly more complicated than that - look at the sample input/output examples.

1 Like

This might work:

echo 'His phone number is (123) 456-7890 and account is 34567 887272. ' | awk '
        {while (match ($0, /[0-9()-]+ *[0-9()-]*/))     {X = substr ($0, RSTART, RLENGTH-4)
                                                         gsub (/[0-9]/, "*", X)
                                                         printf "%s%s%s", substr ($0, 1, RSTART-1), X, substr ($0, RSTART + RLENGTH - 4, 4)
                                                         $0 = substr ($0, RSTART + RLENGTH)
                                                        }
         print
        }
'
His phone number is (***) ***-7890 and account is ***** **7272. 

The regex needs to be quite cumbersome as my mawk doesn't allow for back references. It will fail, too, if there are non-digits in the last four places.

2 Likes