views:

4418

answers:

4

I'm trying to learn bash string handling. How do I create a bash script which is equivalent to this Java code snippet?

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.

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_"?

+4  A: 

That is so simple, Bash does it in the input parser. No code required. Try:

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
unwind
piping the output of echo to `sed -e 's|\ |\n|g' ` works on the first example to split the output into lines.
Ken Gentle
@Ken G: Nice addition!@unwind: While I liked the first example I selected it as my accepted answer for the second one, as it lets me maintain the list in one place only and has the line breaks correctly without having to use Sed (which is available in most places, but not everywhere).
DeletedAccount
Just a little follow up question: Is there a way to do this with a string without spaces separating sub-strings? Like LIST="abcdef12345_"?
DeletedAccount
+1  A: 
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 bash is your friend. It has large sections on its variable replacement and internal commands.

Bombe
While man bash is my friend I find it a bit long to browse through (~4900 rows) if you don't know what you're looking for. In those cases I often Google for a tutorial and if that doesn't help me I try asking here.
DeletedAccount
Yeah, the man page is huge. But I recommend skipping over at least the section titles once so you at least know what’s in it. You can always go back and read more if you need it.
Bombe
+1  A: 

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
Tuminoid
+1  A: 

Just some variation of how you can split the items generated. Personally, i like to use tr for this job. :

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"
Johannes Schaub - litb