2

我需要一个大文件,例如:

member: cn=user0001,ou=people

并随机替换所有用户名,使它们在相同位置仍然有字母,在相同位置有数字。所以输出可能是这样的:

member: cn=kvud7405,ou=people

用户名的长度和格式各不相同,但它们始终以 cn= 和逗号为界。

任何人都可以提供一个最好使用 sed/awk/bash 的解决方案,否则 python 可能是一个选项(不确定哪个版本)。

提前致谢。

4

3 回答 3

5

就像是

sed -i 's/blah/blah?$(cat /dev/urandom | tr -dc "a-z0-9" | fold -w 6 | head -n 1)/g' /home/test.html
于 2012-06-22T14:21:24.560 回答
3
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}'

分成多行:

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
}'

如果需要,可以轻松修改它以处理大写字母字符。

编辑:

更健壮:

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)}'

此版本不使用FS,因此在有其他字段时可以使用。

于 2012-06-22T14:36:47.127 回答
1

一个 Bash 解决方案:

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
于 2012-06-22T15:59:11.013 回答