简体   繁体   中英

How to grep a string in a program?

#include <stdlib.h>

int foo(char *str_buf_to_grep)
{
    // How to write the following line correctly?
    return system("??? str_buf_to_grep ??? | grep mykeyword"); 
}

Description:

  1. The str_buf_to_grep is given in any way, which might be the content of a text file, and might be very long and complex, even contains special characters, such as | , " , etc.

  2. I want to use the grep command to find matched lines, and the patterns might be very complex.

How should I implement it?

Technically, what you are looking for is this:

char cmd[1024];
sprintf(cmd, "echo '%s' | grep mykeyword", str_to_grep);
return system(cmd);

This won't work if your str_to_grep includes single quotes (') in it. You would need to replace single quotes with slash+quote (\\') in order to avoid shell interpolation.

However, I can't understand why would you want to shell out to grep command, rather than use strstr() function, like this:

strstr(str_to_grep, "mykeyword");

The latter is always more efficient, less typing, more portable, and less error prone.

Use popen:

FILE* file = popen( "grep mykeyword", "r" );
fwrite( str_to_grep, 1, strlen( str_to_grep ), file );
pclose( file );

The echo example by Matt might not work as expected if the string has quotes or similar character interpreted specially by the shell.

I assume your example with grep is just for purposes of asking the question - because like Matt said, it would in all ways be better and faster to look for substrings yourself with a strstr loop or similar.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM