But you can't just substitute arbitrary text in a text file, unless it happens to have exactly the same length. As file_b is being read and searched, each line should be copied out to a new file, and updated line printed in it's proper order, and the remainder of file_b copied. Then rename the new file to file_b (making sure file_b is closed).