bash。如何从包含多行的变量中选择随机行?
bash. How to pick random line from a variable containing numerous lines?
a=$(find ./ -name "*-*.txt")
现在我需要从 $a 获取随机线,但是 shuf 对我大吼大叫
b=$(shuf -n1 $a)
shuf: 额外的操作数
我的问题是什么?
谢谢!
您可以为此使用 $RANDOM。
备注:
${#array[@]}
给出数组的大小
$((min + RANDOM % max))
给你一个随机整数,而 max
不包括在内。
- 您可以像这样访问索引
index_number
处的数组项 ${array[index_number]}
# define array
a=()
while read line
do
# read the file list line by line and add to the array
a+=("$line")
done < <(find ./files -name '*-*.txt')
random_index=$((0 + RANDOM % ${#a[@]}))
echo ${a[$random_index]}
默认情况下,shuf
采用单个文件名参数,并随机播放该文件的内容。您希望它改组其参数;为此,使用 shuf -e
:
b=$(shuf -e -n1 $a)
顺便说一句,这有一个更微妙的问题:它会被带有空格 and/or 通配符的文件名混淆。也许不会在您的环境中发生,但我更喜欢使用不会因有趣的文件名而失败的脚本习语。为了防止这种情况,将文件名存储在一个数组中,而不是依靠分词来判断一个停止和下一个开始的位置:
readarray -d '' -t arr < <(find ./ -name "*-*.txt" -print0)
b=$(shuf -en1 "${arr[@]}")
如果不需要存储文件列表,事情就更简单了:
b=$(find ./ -name "*-*.txt" -print0 | shuf -zn1 | tr -d '[=12=]')
a=$(find ./ -name "*-*.txt")
现在我需要从 $a 获取随机线,但是 shuf 对我大吼大叫
b=$(shuf -n1 $a)
shuf: 额外的操作数
我的问题是什么? 谢谢!
您可以为此使用 $RANDOM。
备注:
${#array[@]}
给出数组的大小$((min + RANDOM % max))
给你一个随机整数,而max
不包括在内。- 您可以像这样访问索引
index_number
处的数组项${array[index_number]}
# define array
a=()
while read line
do
# read the file list line by line and add to the array
a+=("$line")
done < <(find ./files -name '*-*.txt')
random_index=$((0 + RANDOM % ${#a[@]}))
echo ${a[$random_index]}
默认情况下,shuf
采用单个文件名参数,并随机播放该文件的内容。您希望它改组其参数;为此,使用 shuf -e
:
b=$(shuf -e -n1 $a)
顺便说一句,这有一个更微妙的问题:它会被带有空格 and/or 通配符的文件名混淆。也许不会在您的环境中发生,但我更喜欢使用不会因有趣的文件名而失败的脚本习语。为了防止这种情况,将文件名存储在一个数组中,而不是依靠分词来判断一个停止和下一个开始的位置:
readarray -d '' -t arr < <(find ./ -name "*-*.txt" -print0)
b=$(shuf -en1 "${arr[@]}")
如果不需要存储文件列表,事情就更简单了:
b=$(find ./ -name "*-*.txt" -print0 | shuf -zn1 | tr -d '[=12=]')