Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an equivalent to Python's expandvars in C?

I have a string stored in a file that is read into a string. I wish to replace variables defined in *nix shell format with the corresponding environment values.

For example, an environment variable of $DEPLOY=/home/user will turn "deploypath=$DEPLOY/dir1" into "deploypath=/home/user/dir1"

Is there a simple library to do this?

i.e.

#include "supersimplelib.h"
char *newstr = expandvars(oldstr);

(or similar)

I understand I could use a regular expression lib and then call getenv() but I was wondering if there was another simpler way?

It will only be compiled under Linux.

like image 332
alfred Avatar asked Jun 30 '11 00:06

alfred


1 Answers

wordexp appears to do what you need. Here's a modified version of an example program from this manpage (which also gives a lot of excellent detail on wordexp).

#include <stdio.h>
#include <wordexp.h>
int main(int argc, char **argv) {
        wordexp_t p;
        char **w;
        int i;
        wordexp("This is my path: $PATH", &p, 0);
        w = p.we_wordv;
        for (i=0; i<p.we_wordc; i++)
                printf("%s ", w[i]);
        printf("\n");
        wordfree(&p);
        return 0;
}

This produces the following output on my machine (Ubuntu Linux 10.04, used gcc to compile).

$ ./a.out 
This is my path: /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games 

I found the manpage above to be most useful, but there's also more information from the GNU C Library Reference Manual.

like image 51
Jacinda Avatar answered Oct 12 '22 23:10

Jacinda