如何创建随机组合指定项列表的bash脚本?
假设我有两个项目列表如何创建随机组合指定项列表的bash脚本?,bash,shell,Bash,Shell,假设我有两个项目列表 Honda Toyota Ford BMW & 我要写一个bash脚本,将这个列表与随机配置结合起来。我该怎么做 示例输出: Honda Black BMW Yellow Ford White Toyota Red 你可以这样做。创建颜色和品牌的简化版本,然后将它们组合在一起 #!/bin/bash shuf brands.txt > brands_shuffeled.txt shuf colors.txt > colors_shuffeled.txt p
Honda
Toyota
Ford
BMW
&
我要写一个bash脚本,将这个列表与随机配置结合起来。我该怎么做
示例输出:
Honda Black
BMW Yellow
Ford White
Toyota Red
你可以这样做。创建颜色和品牌的简化版本,然后将它们组合在一起
#!/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
答案下面的注释表示您希望将无序列表存储在脚本本身中,而不是依赖外部实用程序。虽然可以在脚本中调用实用程序,但也可以在bash中使用数组在脚本中“存放项目列表”。(虽然不清楚您指的是最终列表还是初始列表,但您使用复数形式表示初始列表) 要以无序顺序将文件中的列表存储在脚本中的数组中,只需使用命令替换,例如
brands=( $(shuf brands.txt) ) ## fill brands array with shuffled brands.txt
colors=( $(shuf colors.txt ) ) ## fill colors array with shuffled colors.txt
(如果您想要原始的非缓冲列表,只需将
shuf
替换为它只是+。我明白了。有没有办法将项目列表放在脚本本身中而不是外部调用它?数组,例如brands=($(shuf brands.txt))
和colors=($(shuf colors.txt))
。当然,如果要存储它们,还必须将这些组合放在一起,这可以通过C-stylefor
循环实现。
brands=( $(shuf brands.txt) ) ## fill brands array with shuffled brands.txt
colors=( $(shuf colors.txt ) ) ## fill colors array with shuffled colors.txt
for ((i = 0; i < limit; i++)); do
printf "%s %s\n" "${brands[i]}" "${colors[i]}"
done
#!/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