CS 1713 Section 3, Spring 1997
For this assignment, you will write a Unix command called replace
that will read a file from the standard input, replace each occurence
of a certain string with another string, and print the result to the
Assignment 6: Strings: Search and Replace
Search and Replace
A common function in many editors and word processors is to search for
all occurences of a word or string and replace it with a different string.
For instance, suppose you're writing a paper on The BeeGees and then
realize you were supposed to be writing about ABBA. You issue an instruction
to the word processor to replace all occurences of "The BeeGees" with "ABBA",
and all occurences of "the USA" with "Sweden", and then you're done.
Your assigment is to write a program called replace that accepts
two command line parameters and reads from standard input (whose file
pointer we all know is stdin), and writes to the standard output
(stdout). The program will replace all occurences of the first
command line parameter with the second command line parameter. For instance,
if you type:
runner% replace foo bar
and then type the following at the keyboard:
the word "foo" is a common name for a variable; but no one knows
what kind of food a cat named Shakesfoo likes. Bacon, maybe?
(^D is CTRL-D, signifying the end of file) the output should be
the word "bar" is a common name for a variable; but no one knows
what kind of bard a cat named Shakesbar likes. Bacon, maybe?
The program should work for any length file. You should use fgets()
to get the lines from the file; if you use fscanf the program won't
work properly when it comes to whitespace. You may assume that no single
string in the input file will be longer than 1000 characters (although
the input file may contain arbitrarily many lines).
- Look into the strstr() function. It returns a pointer to
the first occurence of a certain substring in a string, or NULL
(the null pointer, zero) if
the string isn't found. You can use this pointer as a starting point for
where to replace.
- Replace every occurence, not just the first occurence in
the line. How will you do this? How about a while loop that keeps modifying
the string until strstr() returns NULL? But what if argv
and argv are the same string?
- A search string is not necessarily a word. It may have spaces in it,
punctuation, etc., so there are no special characters in this assignment.
- A good way to find text files to test your program on is from a newsgroup.
Find someone's article and save it to your
directory (use the 's' command in trn; the article will be
saved in the News directory in your home directory).
- Your program should normally be run with standard input and output
redirected using the shell < and > characters, e.g.
- The program findstring.c presented
in class goes about halfway into doing this assignment for you. You may
use it if you like.
replace Hello Goodbye < file1 > file2
This assignment is due Wednesday, March 12, 1997 at midnight.