sed-style用随机字母替换字母,用随机数字替换数字

时间:2012-06-22 14:19:07

标签: bash replace sed awk

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

member: cn=user0001,ou=people

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

member: cn=kvud7405,ou=people

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

任何人都可以提供sed / awk / bash的解决方案,或者说python可能是一个选项(不确定是哪个版本)。

提前致谢。

3 个答案:

答案 0 :(得分:5)

类似

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

答案 1 :(得分: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,因此在有其他字段时可以使用。

答案 2 :(得分: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