rich
rich

Reputation: 19414

sed-style replace letters with random letters, numbers with random numbers

I need to take a large file, with lines such as:

member: cn=user0001,ou=people

And replace all the usernames such that they still have letters in the same position and numbers in the same position, at random. So the output might be something like:

member: cn=kvud7405,ou=people

The usernames vary in length and format, but they're always bounded by a cn= and a comma.

Can anyone offer a solution with sed/awk/bash preferably, or failing that python might be an option (not sure which version).

Thanks in advance.

Upvotes: 2

Views: 4580

Answers (3)

Dennis Williamson
Dennis Williamson

Reputation: 360153

awk -F 'cn=|,' 'BEGIN {srand(); OFS = ""} {n = split($2, a, ""); for (i = 1; i <= n; i++) {if (a[i] ~ /[[:digit:]]/) {new = new int(rand() * 10)} else {new = new sprintf("%c", int(rand() * 26 + 97))}}; $2 = "cn=" new ","; print}'

Broken out on multiple lines:

awk -F 'cn=|,' '
    BEGIN {
        srand(); 
        OFS = ""
    } 
    {
        n = split($2, a, ""); 
        for (i = 1; i <= n; i++) {
            if (a[i] ~ /[[:digit:]]/) {
                new = new int(rand() * 10)
            }
            else {
                new = new sprintf("%c", int(rand() * 26 + 97))
            }
        }; 
        $2 = "cn=" new ","; 
        print
}'

It could easily be modified to handle uppercase alpha characters if needed.

Edit:

More robust:

awk 'BEGIN {srand()} {match($0, /cn=[^,]*,/); n = split(substr($0, RSTART+3, RLENGTH-4), a, ""); for (i = 1; i <= n; i++) {if (a[i] ~ /[[:digit:]]/) {new = new int(rand() * 10)} else {new = new sprintf("%c", int(rand() * 26 + 97))}}; print substr($0, 1, RSTART+2) new substr($0, RSTART+RLENGTH-1)}'

This version doesn't use FS so it works when there are additional fields.

Upvotes: 3

Fritz G. Mehner
Fritz G. Mehner

Reputation: 17198

A Bash solution:

letter=( a b c d e f g h i j k l m n o p q r s t u v w x y z )
digit=( 0 1 2 3 4 5 6 7 8 9 0 )
while read line; do
  user=''
  line=${line#*=}                           # separate cn-value
  line=${line%,*}                           # separate cn-value
  for (( CNTR=0; CNTR<${#line}; CNTR+=1 )); do
    if [[ ${line:CNTR:1} =~ [[:alpha:]] ]] ; then
      user=$user${letter[RANDOM%26]}
    else
      user=$user${digit[RANDOM%10]}
    fi
  done
  echo  "member: cn=${user},ou=people"
done < "$infile" > "$tempfile"

mv "$tempfile" "$infile"                    # replace original file

Upvotes: 1

HaloWebMaster
HaloWebMaster

Reputation: 928

something like

sed -i 's/blah/blah?$(cat /dev/urandom | tr -dc "a-z0-9" | fold -w 6 | head -n 1)/g' /home/test.html

Upvotes: 5

Related Questions