所以可以说我有3行代码
ABC
123
!@#
我如何创建for循环以输出将它们组合在一起的方式数量?
E ABC123!@#, ABC!@#123, 123ABC!@#$
这是我当前的代码行
#!/bin/bash
alphabet='ABC' numbers='123' special='!@#'
for name in $alphabet$numbers$special
do
echo $name
done
echo done
答案 0 :(得分:1)
alphabet='ABC' numbers='123' special='!@#'
for name1 in $alphabet $numbers $special
#on 1st iteration, name1's value will be ABC, 2nd 123 ...
do
for name2 in $alphabet $numbers $special
do
for name3 in $alphabet $numbers $special
do
#here we ensure that we want strings only as combination of that three strings
if [ $name1 != $name2 -a $name2 != $name3 ]
then
echo $name1$name2$name3
fi
done
done
done
如果您还希望打印字符串,例如 123123123 和 ABCABCABC ,请在有条件的情况下删除
答案 1 :(得分:1)
您还可以使用括号扩展完全没有循环地执行此操作(但是您会失去排除功能,例如ABCABCABC
)。例如:
#!/bin/bash
alpha='ABC'
num='123'
spec='!@#'
printf "%s\n" {$alpha,$num,$spec}{$alpha,$num,$spec}{$alpha,$num,$spec}
使用/输出示例
$ bash permute_brace_exp.sh
ABCABCABC
ABCABC123
ABCABC!@#
ABC123ABC
ABC123123
ABC123!@#
ABC!@#ABC
ABC!@#123
ABC!@#!@#
123ABCABC
123ABC123
123ABC!@#
123123ABC
123123123
123123!@#
123!@#ABC
123!@#123
123!@#!@#
!@#ABCABC
!@#ABC123
!@#ABC!@#
!@#123ABC
!@#123123
!@#123!@#
!@#!@#ABC
!@#!@#123
!@#!@#!@#