如何在字符串中的任何位置随机添加单个特殊字符?巴什

时间:2014-10-25 00:14:33

标签: linux bash unix

我有这个脚本,可以生成8-16之间的随机字符。我很困惑如何在这个字符串中随机的任何地方从一个银行[! @ # $ % ^ & * ( ) _ + ]添加一个随机特殊字符?

if [ $# -eq 0 ] then    
    pwdlen=$(((RANDOM % 9 ) +8))   
    spclen=$((RANDOM % 1))

    char=(0 1 2 3 4 5 6 7 8 9 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 A B C D E F G H I J K L M N O P Q R S T U V X W Y Z)

    chars=(~ ! @ # $ % ^ & * - +)    
    #rand2=$random % 11

    max=${#char[*]}    
    for i in `seq 1 $pwdlen`
    do
        let "rand=$RANDOM % $max"
        str="${str}${char[$rand]}"
    done    
    echo $str    
    exit 0 
fi

3 个答案:

答案 0 :(得分:2)

teststring=foobarspam

specialchars='!@#$%^&*()_+'

randomchar=${specialchars:RANDOM % ${#specialchars}:1}
randompos=$(( RANDOM % ( ${#teststring} + 1 ) ))
newstring=${teststring:0:randompos}${randomchar}${teststring:randompos}

答案 1 :(得分:0)

我不确定您使用的是哪种脚本语言。我使用PHP为您编写了一个解决方案。如果PHP不是您正在使用的,您应该能够将相同的逻辑转换为其他语言并获得相同的结果。

<?php
//This is the original string where you want to add a random character to
$org_string = 'This is My original String';
//calculates the length of the string
$org_length = strlen($org_string);
//find a random position
$pos = rand(0, $org_length-1);

//concatenate the first part of the string, random character, the remaining string
$final = substr($org_string, 0, $pos) . getOne() . substr($org_string, $pos);

//print the final value
echo $final;

//return a random string
function getOne(){
    //the following string is 12 characters in length. it is all available characters that you want to select from
    $str = '!@#$%^&*()_+';
    //return a random character
    return $str[rand(0, 11)];
}

?>

答案 2 :(得分:0)

您可以使用以下代码。

#!/bin/bash

if [ $# -eq 0 ]; then
    pwdlen=$(((RANDOM % 9 ) +8))
    spclen=$((RANDOM % 1))

    char=(0 1 2 3 4 5 6 7 8 9 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 A B C D E F G H I J K L M N O P Q R S T U V X W Y Z)

    chars=('~' '!' '@' '#' '$' '%' '^' '&' '*' '-' '+')
    #rand2=$random % 11

    max=${#char[*]}
    for i in `seq 1 $pwdlen`
    do
        let "rand=$RANDOM % $max"
        str="${str}${char[$rand]}"
    done
    A=$(echo $str|wc -c) ## To get the count of 
    P=$((RANDOM % $A)) ## To get a random position of where to insert the character.
    I=$((RANDOM % 11)) ## To get a random index number of chars array
    C=${chars[$#]}
    echo $str | sed 's!^\(.\{'$P'\}\).!\1\'"$C"'!'  ## Inserting the special character to string in defined position
    exit 0
fi

输出:

$ for i in `seq 1 10`;do ./test1;done
j^eh8BmD2H
0B01^1AN6EVw
Wu2$LLTILuDN8fSV
e^90gmHjksDo
eB7wa\#fmwf
NVAtJkmfqx~
JaHvD%uyO3rB
ncFrgyyz~UkZ
q0LLRHUNATM8DL
X%ARcXgyC1Do