Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

reading and writing same file 3

Status
Not open for further replies.

liv4jc

Programmer
May 10, 2002
6
0
0
CA
I need to search a file for a specific string, then modify the line where that string is. How can I read a file, remember my place in the file, and modify the file at that place? Thanks.
 
I guess what I would do is open file A for reading, and file B for writing. Read from file A, line by line - if the line doesn't contain the string you're looking for, then just write the line to file B - if the line does contain the string you're for, then write the "changed" line to file B.

You end up with file B which is the same as file A, except that the string you were looking for has been found and changed in file B.

When that loop has finished, you can "move" file B to file A - you basically want to remove the original file A, and rename file B to file A. There are at least a few ways to accomplish that.

As you're writing your code, test it along the way. If you have trouble with a specific part, post your problem and someone can help you.

HTH. Hardy Merrill
 
Check out the -i flag to perl:

perl -i.bak -p -e 's/oldstring/newstring/;' myfile

will change all the oldstrings to newstrings in place in
myfile and make you a myfile.bak backup copy of the
old file.

You can also use the -i flag inside a script on the
'she-bang' like at the beginning -- something like

#!/usr/bin/perl -i.bak
while (<>) {
s/oldstring/newstring/;
print;
}

will achieve a similar effect to the -pe example above. See
% perldoc perlrun
or
for more on the -i flag, including more examples.
 
Good job bbacker! I don't know what I was thinking. Of course the &quot;s&quot;ubstitute function is the way to go. Hardy Merrill
 
Yea - I've not much experience with that sort of thing. I like that solution - very elegant - it's a utility that's available just for such situations.
That does deserve a star. Supa-star!

--jim
 
Actually, I'm not simply substituting one string for another. I need to do some more processing according to another input file. So I think I'll need to do what hmerril suggested the first time. Thank you both!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top