#include #include #include int find_new_index(char *pattern, int index, int newstart); int main(int argc, char **argv) { int index=0, patlen, replen; int symbol; char *pattern, *replacement; if ( argc < 2 ) { printf("Usage: %s pattern replacement\n", argv[0]); return 1; } pattern=argv[1]; replacement=argv[2]; patlen=strlen(pattern); replen=strlen(replacement); while ( (symbol=getchar()) != EOF ) { if ( index == patlen) { write(fileno(stdout), replacement, replen); index = 0; } restart: if ( symbol == pattern[index] ) { index++; } else { if ( index ) { int to_print = find_new_index(pattern, index, 1); write(fileno(stdout), pattern, to_print); index -= to_print; goto restart; } else { write(fileno(stdout), &symbol, 1); // XXX - won't work on bigendian } } } write(fileno(stdout), pattern, index); return 0; } int find_new_index(char *pattern, int index, int newstart) { int i; for ( i = 0; i+newstart < index ; i++) { if ( pattern[newstart+i] != pattern[i] ) { return i + find_new_index(pattern, index, newstart+1); } } return newstart; }