grep
The grep Command
grep searches for a pattern in text and prints every line that contains it:
$ grep "Linux" notes.txt
Learn Linux
Only lines containing "Linux" are printed. Lines without it are discarded.
Your Implementation
Write void my_grep(const char *s, const char *pat) that prints every line in s that contains the substring pat.
You need two sub-problems:
- Split the input into lines (scan for
'\n') - Check if a line contains the pattern (substring search)
For substring search, use two pointers — one walking the haystack, one walking the needle:
int contains(const char *hay, const char *needle) {
for (; *hay; hay++) {
const char *h = hay, *n = needle;
while (*n && *h == *n) { h++; n++; }
if (!*n) return 1;
}
return 0;
}
For each position in hay, try to match the full needle starting there. If n reaches the null terminator, the full needle matched.
Then collect each line into a buffer with a pointer, check if it contains the pattern, and print it if so.
Why Nested Loops?
The contains function is O(n × m) where n is the line length and m is the pattern length. For every position in the haystack, it tries to match the full needle. This is the naive algorithm.
Real grep uses algorithms like Boyer-Moore or Knuth-Morris-Pratt that are faster in practice, but for learning purposes, the nested loop is perfectly clear.
Your Task
Implement my_grep that prints lines containing the given pattern.