创建一个函数来选择一个随机子字符串:
random_string() {
line=$1
length=$2
# make sure we start at a random position that guarantees a substring of given length
start=$((RANDOM % ((${#line} - $length))))
# use Bash brace expansion to extract substring
printf '%s' "${line:$start:$length}"
}
循环使用函数:
#!/bin/bash
while IFS= read -r line; do
random1=$(random_string "$line" 3)
random2=$(random_string "$line" 20)
printf 'random1=[%s], random2=[%s]\n' "$random1" "$random2"
done < file
在file 中包含内容Welcome to stackoverflow the best technical resource ever 的示例输出:
random1=[hni], random2=[low the best technic]
random1=[sta], random2=[e best technical res]
random1=[ove], random2=[ackoverflow the best]
random1=[rfl], random2=[echnical resource ev]
random1=[ech], random2=[est technical resour]
random1=[cal], random2=[ome to stackoverflow]
random1=[tec], random2=[o stackoverflow the ]
random1=[l r], random2=[come to stackoverflo]
random1=[erf], random2=[ stackoverflow the b]
random1=[me ], random2=[ the best technical ]
random1=[est], random2=[ckoverflow the best ]
random1=[tac], random2=[tackoverflow the bes]
random1=[e t], random2=[o stackoverflow the ]
random1=[al ], random2=[come to stackoverflo]