dejunl
dejunl

Reputation: 57

sed command works fine under shell terminal, but fails in 'system()' call under C code

I'm trying to delete some special lines in a log file, so I use sed of busybox on an embeded linux system.

# sed
BusyBox v1.18.4 (2013-01-16 16:00:18 CST) multi-call binary.

Usage: sed [-efinr] SED_CMD [FILE]...

Options:
        -e CMD  Add CMD to sed commands to be executed
        -f FILE Add FILE contents to sed commands to be executed
        -i      Edit files in-place (else sends result to stdout)
        -n      Suppress automatic printing of pattern space
        -r      Use extended regex syntax

If no -e or -f, the first non-option argument is the sed command string.
Remaining arguments are input files (stdin if none).
  1. execute the following command under shell and everything works fine:

    export MODULE=sshd
    sed "/$MODULE\[/d" logfile
    
  2. but if I try to use the following C code to accomplish this:

    char logfile[] = "logfile";
    char module_str[] = "sshd";
    char env_str[64] = {0};
    int offset = 0;
    
    strcpy(env_str, "MODULE=");
    offset += strlen("MODULE=");
    strcpy(env_str + offset, module_str);
    putenv(env_str);
    system("sed \"/$MODULE\[/d\" logfile");
    

when executing the a.out, I got the error message:

sed: unmatched '/'

what's wrong with my 'system()' call? I'm totally a newbie in text processing, so anybody can give me some clue? Thanks.

Best regards, dejunl

Upvotes: 2

Views: 1672

Answers (1)

Jasen
Jasen

Reputation: 12402

straight off I can see that the \ before the [ is going to be swallowed by 'C'

so you'll need to double it,

system("sed \"/$MODULE\\[/d\" logfile");

But the shell might want to swallow the one that's left swallow that one so double it again

system("sed \"/$MODULE\\\\[/d\" logfile");

of course system("sed \"/$MODULE\\[/d\" logfile"); can't be sure I'm reading the question you posed. try it with echo instead of sed and adjust it until the string comes out as you want sed to see it.

Upvotes: 2

Related Questions