Shell脚本,三组名称,每个组合

时间:2017-11-08 23:18:24

标签: bash list shell combinations

我正在尝试编写一个shell脚本,它接受三个名称列表,并从列表中找到每个组合,每个列表上可能有不同数量的名称。

清单1
迈克
汤姆
哈利
史蒂夫

清单2
德博拉
萨拉

清单3
亚历克斯

凯利
阿曼达

菲利普
大卫

从列表1中取出Mike然后从列表2中取出Deborah然后列出列表3中的所有名称。然后再从列表1中取出Mike,从列表2中取出Sarah,然后列出列表3中的所有名称等,直到它为止。我们提出了各种可能的组合。

在思考如何实现这一目标时遇到一些困难,我们将不胜感激。

2 个答案:

答案 0 :(得分:2)

您可以使用for循环。设f1,f2和f3为包含三个列表的文件。然后:

for a in `cat f1`;do
 for b in `cat f2`;do
  for c in `cat f3`;do
   echo $a $b $c;
  done;
 done;
done

例如:

$ cat f1
red
green
cat

$ cat f2
rice
bread
cat f

$ cat f3
tomato
onion


$ for a in `cat f1`;do for b in `cat f2`;do for c in `cat f3`;do echo $a $b $c; done; done; done
red rice tomato
red rice onion
red bread tomato
red bread onion
green rice tomato
green rice onion
green bread tomato

答案 1 :(得分:1)

根据您存储list x的方式,您只需使用大括号扩展将所有三个列表置于一起,例如:

printf "%s\n" {Mike,Tom,Harry,Steve}\
{Deborah,Sarah,Jennifer}\
{Alex,Joe,Kelly,Amanda,Will,Phillip,David}

示例使用/输出

$ bash brexpperm.sh
MikeDeborahAlex
MikeDeborahJoe
MikeDeborahKelly
MikeDeborahAmanda
MikeDeborahWill
MikeDeborahPhillip
MikeDeborahDavid
MikeSarahAlex
MikeSarahJoe
MikeSarahKelly
MikeSarahAmanda
MikeSarahWill
MikeSarahPhillip
MikeSarahDavid
MikeJenniferAlex
MikeJenniferJoe
MikeJenniferKelly
MikeJenniferAmanda
MikeJenniferWill
MikeJenniferPhillip
MikeJenniferDavid
TomDeborahAlex
TomDeborahJoe
TomDeborahKelly
TomDeborahAmanda
TomDeborahWill
TomDeborahPhillip
TomDeborahDavid
TomSarahAlex
TomSarahJoe
TomSarahKelly
TomSarahAmanda
TomSarahWill
TomSarahPhillip
TomSarahDavid
TomJenniferAlex
TomJenniferJoe
TomJenniferKelly
TomJenniferAmanda
TomJenniferWill
TomJenniferPhillip
TomJenniferDavid
HarryDeborahAlex
HarryDeborahJoe
HarryDeborahKelly
HarryDeborahAmanda
HarryDeborahWill
HarryDeborahPhillip
HarryDeborahDavid
HarrySarahAlex
HarrySarahJoe
HarrySarahKelly
HarrySarahAmanda
HarrySarahWill
HarrySarahPhillip
HarrySarahDavid
HarryJenniferAlex
HarryJenniferJoe
HarryJenniferKelly
HarryJenniferAmanda
HarryJenniferWill
HarryJenniferPhillip
HarryJenniferDavid
SteveDeborahAlex
SteveDeborahJoe
SteveDeborahKelly
SteveDeborahAmanda
SteveDeborahWill
SteveDeborahPhillip
SteveDeborahDavid
SteveSarahAlex
SteveSarahJoe
SteveSarahKelly
SteveSarahAmanda
SteveSarahWill
SteveSarahPhillip
SteveSarahDavid
SteveJenniferAlex
SteveJenniferJoe
SteveJenniferKelly
SteveJenniferAmanda
SteveJenniferWill
SteveJenniferPhillip
SteveJenniferDavid

或者,如果您需要空格,只需在扩展中添加一个:

printf "%s\n" {'Mike ','Tom ','Harry ','Steve '}\
{'Deborah ','Sarah ','Jennifer '}\
{Alex,Joe,Kelly,Amanda,Will,Phillip,David}

示例使用/输出

$ bash brexpperm.sh
Mike Deborah Alex
Mike Deborah Joe
Mike Deborah Kelly
Mike Deborah Amanda
...
Steve Jennifer Amanda
Steve Jennifer Will
Steve Jennifer Phillip
Steve Jennifer David

如果您无法控制脚本本身的列表,那么循环解决方案可以正常工作。