我想替换子串" [i]"使用bash的一些随机数。 e.g。
abc.[i].xyz[i].lmn[i]
输出应为
abc.3.xyz.5.lmn.32
这里3,5,52是随机生成的数字。
答案 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范围内。