11

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.

sarnold
  • 102,305
  • 22
  • 181
  • 238
alfred
  • 639
  • 1
  • 6
  • 11
  • Can or should I answer my own question? I have found this [wordexp](http://pubs.opengroup.org/onlinepubs/007908799/xsh/wordexp.html) and it is what I was after. – alfred Jun 30 '11 at 01:24
  • Yes, you can (and should). See the [FAQ](http://stackoverflow.com/faq). – Matthew Flaschen Jun 30 '11 at 01:25
  • I cant for another 7 hours :) so ill use this comment to placehold my answer: I found this and it is what I am after [wordexp](http://pubs.opengroup.org/onlinepubs/007908799/xsh/wordexp.html) I also found a related question which also has the same answer. [link](http://stackoverflow.com/questions/1902681/expand-file-names-that-have-environment-variables-in-their-path) – alfred Jun 30 '11 at 01:30
  • Was writing my answer while you were posting this... – Jacinda Jun 30 '11 at 01:39
  • FWIW, Windows has the [`ExpandEnvironmentStrings`](http://msdn.microsoft.com/en-us/library/ms724265%28v=vs.85%29.aspx) function for doing just this, but it's not portable. – Adam Rosenfield Jun 30 '11 at 03:11

1 Answers1

7

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.

Jacinda
  • 4,932
  • 3
  • 26
  • 37