Bash 字符串处理(索引和连接处的字符)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/349702/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Bash string handling (char at index and concatenation)
提问by unwind
I'm trying to learn bash string handling. How do I create a bash script which is equivalent to this Java code snippet?
我正在尝试学习 bash 字符串处理。如何创建与此 Java 代码片段等效的 bash 脚本?
String symbols = "abcdefg12345_";
for (char i : symbols.toCharArray()) {
for (char j : symbols.toCharArray()) {
System.out.println(new StringBuffer().append(i).append(j));
}
}
The output of the above code snippet starts with:
上面代码片段的输出开始于:
aa
ab
ac
ad
ae
af
And ends with:
并以:
_g
_1
_2
_3
_4
_5
__
My goal is to have a list of allowed characters (not necessarily the ones above) and print out all the permutations of length 2. If it is possible I would like a solution which relies solely on bash and doesn't require anything else installed.
我的目标是有一个允许的字符列表(不一定是上面的那些)并打印出长度为 2 的所有排列。如果可能的话,我想要一个仅依赖于 bash 并且不需要安装任何其他东西的解决方案。
Edit:Just a little follow up question: Is there a way to do this with a string without spaces separating sub-strings? Like LIST="abcdef12345_"?
编辑:只是一个小小的后续问题:有没有办法用没有空格分隔子字符串的字符串来做到这一点?喜欢 LIST="abcdef12345_"?
回答by unwind
That is so simple, Bash does it in the input parser. No code required. Try:
就是这么简单,Bash 在输入解析器中做到了。无需代码。尝试:
echo {a,b,c,d,e,f,g,1,2,3,4,5,_}{a,b,c,d,e,f,g,1,2,3,4,5,_}
You might need a second pass to split it into lines, though.
不过,您可能需要第二遍才能将其拆分为几行。
Or, you could of course use a couple of nested loops like in your example:
或者,您当然可以在示例中使用几个嵌套循环:
LIST="a b c d e f 1 2 3 4 5 _";
for a in $LIST ; do
for b in $LIST ; do
echo $a$b;
done;
done
回答by Bombe
for i in a b c d e f g 1 2 3 4 5 _; do
for j in a b c d e f g 1 2 3 4 5 _; do
echo $i$j
done
done
man bashis your friend. It has large sections on its variable replacement and internal commands.
man bash是你的朋友。它有很大一部分关于其变量替换和内部命令。
回答by Tuminoid
Fits one line nicely:
非常适合一行:
for i in `echo {a,b,c,d,e,f,g,1,2,3,4,5,_}{a,b,c,d,e,f,g,1,2,3,4,5,_}`; do echo $i; done
回答by Johannes Schaub - litb
Just some variation of how you can split the items generated. Personally, i like to use trfor this job. :
只是如何拆分生成的项目的一些变化。就个人而言,我喜欢tr用于这项工作。:
echo {a,b,c,d,e,f,g,1,2,3,4,5,_}{a,b,c,d,e,f,g,1,2,3,4,5,_} | tr " " "\n"

