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 wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

A better way than this to Read and Replace lines in a file

Status
Not open for further replies.

andyros

Programmer
Jul 12, 2005
42
GB
Hey guys

Im wanting to read in from a directory of files and take each file in turn checking for a specific word. Once have have found this word i want to replace it.

I've got a solution but its not really that efficent. It reads all the content of the file and stores it in an array, logs where the word matched then prints everything back out chaning the lines as it finds them.

There's got to be a way I can write to a specific line in a text file?

heres an example

Search for dog:

Read first file from directory
look for line to replace
write over this line
continue searching file for other matches
if no matches move to next file in directory.

Basically all i want to know is if it is possible to replace a specific line in a text file without reading in everything then writing it all out.

thanks in advance
andy
 
The problem is that lines isn't how files work on the disk

123\n
56789\z

is the same size as
1\n
2\n
3\n
4\n
5\n\z

10 bytes each (plus EOF (ctrl-Z || \c26))

so if you start overwriting at position 5 (start of 3\n in file #2) with dog

you end up with

1\n
2\n
dog\n
5\n


Having said that Tie::File on might be the salvation you seek

HTH
--Paul



cigless ...
 
You can do it in one line of perl

Code:
perl -pi -e 's/from/to/g' file_wildcard*

That is assuming that "from" is the text to change from and "to" is the text to change to and "filewildcard*" is some file wildcard selection for all the files you want to process.

Warning! You might do well to use the backup option to create backup files in case anything goes wrong. You do that like this:

Code:
perl -pi.bak -e 's/from/to/g' file_wildcard*


Hope this helps.




Trojan.
 
cheers guys. I tired to use Tie::File but it wouldnt download through ppm for some reason so i've used Trojans way but inside my code.

If anyones intrested its done like this:

Code:
$stringToLookIn =~ s/$patternToSearch/$replaceString/gi;

So i wanted to search for my patternToSearch in stringToLookIn and replace it with replaceString. :)

g means global to ensure i check the whole string, even if one instance of the pattern is found and as im sure you know is just to ignore case.

andy
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top