说我有2个项目列表
Honda
Toyota
Ford
BMW
&
Red
Blue
White
Black
Silver
Yellow
我当时要编写一个bash脚本,将这个列表与随机配置结合在一起。我该怎么做?
示例输出:
Honda Black
BMW Yellow
Ford White
Toyota Red
答案 0 :(得分:2)
您在答案下方的评论表明您希望将改组后的列表存储在脚本本身中,而不是依赖于外部实用程序。虽然您可以在脚本中调用实用程序,但也可以使用bash中的数组在脚本中“放置项目列表”。 (虽然不清楚是指最终列表还是初始列表,但使用复数形式会提示初始列表)。
要将文件中的列表以随机顺序存储在脚本中的数组中,只需使用命令替换即可,例如
brands=( $(shuf brands.txt) ) ## fill brands array with shuffled brands.txt
colors=( $(shuf colors.txt ) ) ## fill colors array with shuffled colors.txt
(如果您想要原始的未打乱列表,只需将shuf
替换为<
)
(注意:,如果任何行都可以包含空格,则需要将内部字段分隔符变量(IFS
)设置为仅在换行符之前填充数组,或者使用mapfile -t
填充数组)
然后从brands
和colors
中选择一个元素以将它们放在一起,只需使用C样式的for
循环将类似的索引放在一起,例如
for ((i = 0; i < limit; i++)); do
printf "%s %s\n" "${brands[i]}" "${colors[i]}"
done
(其中上面的limit
仅是brands
和colors
之间的较少元素)
将整个脚本放在一起并如上所述设置IFS
,您可以执行以下操作:
#!/bin/bash
oifs="$IFS" ## save original IFS (Internal Field Separator)
IFS=$'\n' ## set IFS to only break on newlines (if spaces in lines)
brands=( $(shuf brands.txt) ) ## fill brands array with shuffled brands.txt
colors=( $(shuf colors.txt ) ) ## fill colors array with shuffled colors.txt
IFS="$oifs" ## restore original IFS
limit=${#brands[@]} ## find array with least no. of elements
[ "${#colors[@]}" -lt "$limit" ] && limit=${#colors[@]}
for ((i = 0; i < limit; i++)); do
printf "%s %s\n" "${brands[i]}" "${colors[i]}"
done
运行时会产生随机映射,例如
使用/输出示例
$ bash shuffled.sh
BMW White
Ford Yellow
Honda Black
Toyota Blue
答案 1 :(得分:1)
您可以执行以下操作。创建颜色和品牌的混搭版本,然后将它们组合。
#!/bin/bash
shuf brands.txt > brands_shuffeled.txt
shuf colors.txt > colors_shuffeled.txt
paste -d " " brands_shuffeled.txt colors_shuffeled.txt | grep -v -e "^ " -e ' $'
grep命令仅删除您只具有颜色或品牌的线条,而不是删除两个部分(对于您的数据,我们将仅包含仅颜色的线条,因为颜色多于品牌)。
输出如下:
Toyota Red
Honda Yellow
Ford Blue
BMW White