替换每次出现的" [i]"使用bash在文本文件中使用一些随机数

时间:2014-04-24 07:37:15

标签: bash shell

我想替换子串" [i]"使用bash的一些随机数。 e.g。

abc.[i].xyz[i].lmn[i]

输出应为

abc.3.xyz.5.lmn.32

这里3,5,52是随机生成的数字。

1 个答案:

答案 0 :(得分:2)

#!/bin/bash

# $result replace_random($search, $replace)
#
# replace all occurrences of $replace in $search with a random number
# in the range 0-32767 using bash's built-in PRNG and return the result
replace_random()
{
    local s=$1
    local replace=$2

    # while $s ($search) contains $replace replace the first occurrence
    # of $replace with a random number.
    # quoting "$replace" forces it to be treated as a simple string
    # and not a pattern to avoid e.g. '[i]' being interpreted as a
    # character class (same holds true for '?' and '*')
    while [[ ${s} == *"${replace}"* ]]; do
        s=${s/"${replace}"/$RANDOM}
    done
    echo "${s}"
}

foo='abc.[i].xyz[i].lmn[i].aab'
bar=$(replace_random "${foo}" "[i]")

echo "foo = [$foo]"
echo "bar = [$bar]"

$ ./t.sh
foo = [abc.[i].xyz[i].lmn[i].aab]
bar = [abc.10103.xyz4641.lmn21264.aab]

要强制将随机数放入较小的范围,您可以使用例如

s=${s/"${replace}"/$((RANDOM%64))}

将导致数字在0 - 63范围内。