Search code examples
calgorithmstring-parsingbrace-expansion

Algorithm for BASH/CSH/ZSH style brace expansion


If I have a string like

a/{b,c,d}/e

then I want to be able to produce this output:

a/b/e
a/c/e
a/d/e

You get the idea. I need to implement this in C. I have written a brute force kind of code which i capable of parsing a single pair of braces (for example: /a/{b,c,d}/e/ but if there are multiple pair of braces, like /a/{b,c}/{d,e}/f in that case my method will break. I would like to take a better approach.

I am not asking directly for the code, just a hint towards an efficient algorithm would be sufficient. I think the task of parsing the braces is repetitive and we could follow a recursive algorithm?


Solution

  • If you're on any kind of Unix, Linux or OS X system, there is a built in library function to do this. man 3 glob will tell you about how to call it from C. Or you can visit http://linux.die.net/man/3/glob to find online documentation.

    If you want to roll your own, a simple way to go is to first scan the string and build an intermediate data structure, and then recursively walk that data structure, printing strings. That data structure could be built out of structs with the following fields:

    • text: pointer to a piece of string
    • next_node: pointer to what comes after this text when printed
    • sibling_node: pointer to the next choice that could be made instead of this one