Sunday, 3 October 2021

c program to simulate grep command

 

1. The grep filter searches a file for a particular pattern of characters, and displays all lines that contain that pattern.

Example:

if geekfile.txt contains the data below:

unix is great os. unix is opensource. unix is free os.
learn operating system.

 

Then the following command

$grep -c "unix" geekfile.txt

 

will give ouput:

2

 

as option -c prints only a count of the lines that match a pattern
 
Q) Example program to simulate  grep system call
#include <stdio.h>
#include<string.h>
int main()
{
    char st[1000], word[10];
    printf("enter a sentence");
    scanf(" %[^\n]s", st);
    printf("enter a search word");
    scanf(" %s",word);
    int l = strlen(st);
    int lw=strlen(word);
    char *p;
    int i=0,c=0;
    while(i<l)
    {
        p=strstr(st+i,word);
        if(p)
        {
            c++;
            i=p-st+lw;
        }
        else
            break;
    }
    printf("%s occurred %d times",word,c);
    return 0;
}

 

No comments:

Post a Comment