Solved

Find and replace text in .txt file??

Posted on 1998-09-26
6
185 Views
Last Modified: 2010-04-06
Hello!

I am trying to open a text file called TEST.TXT, find a line of text we'll call "A", then replace it with a new one which we'll call "B", then close the file.

Here is the line I want to find in TEST.TEXT:
LINE A:

Pref("This is the old line", "and more here");

Here is the line I want to replace it with:
LINE B:

Pref("New line I want to use", "and here to");

The replacement would be the entire line from the "P" to the ";"

If anyone has an example, or helpful info I'd sure appreciate it.

Thanks!

-S
0
Comment
Question by:summerset
6 Comments
 
LVL 10

Expert Comment

by:viktornet
ID: 1340906
Here is an example.....
--------------
var
    FileN : string = 'C:\windows\desktop\test.txt';
procedure TForm1.Button1Click(Sender: TObject);
var
      F,F1 : TextFile;
    LineStr : string;
begin
      AssignFile(F, FileN);
    SetLength(FileN, Length(FileN)-3);
    AssignFile(F1, FileN + 'dat');
    Reset(F);
    Rewrite(F1);
    while not EOF(F) do
    begin
            ReadLn(F, LineStr);
        if UpperCase(LineStr) = 'SOME TEXT' then
            WriteLn(F1, 'Another Text')
        else
              WriteLn(F1, LineStr);
    end;
    CloseFile(f);
    CloseFile(f1);
end;
-------------
Regards,
Viktor Ivanov
0
 

Author Comment

by:summerset
ID: 1340907
Hi Viktor:

Thanks for the effort, but it doesn't work properly. Besides, I want to replace the text "in" the same file, not just put it all into a new and differently named file.

-S
0
 

Expert Comment

by:elkiors
ID: 1340908
You could try using the MEMO component, this has LoadFromFile and SaveToFile methods. You could load your text file into the memo and then search and replace within their before saving the file back out.

You could still use victor's answer, by adding a routine to delete the original file and then rename the new file to the original name, if all this is done in the background then it will 'appear' as though you're just stripping down one file

hope this gives some ideas

Darren

0
Live: Real-Time Solutions, Start Here

Receive instant 1:1 support from technology experts, using our real-time conversation and whiteboard interface. Your first 5 minutes are always free.

 

Author Comment

by:summerset
ID: 1340909
Hi Viktor:

Thanks for the effort, but it doesn't work properly. Besides, I want to replace the text "in" the same file, not just put it all into a new and differently named file.

-S
0
 
LVL 5

Accepted Solution

by:
scrapdog earned 50 total points
ID: 1340910
Take a look at ths procedure (which has its own internal functions):
-----------------------------------------


procedure Replace(S :TStrings;
                  OldStr, NewStr  :string;
                  CaseSensitive :boolean);

var
  FirstLine, LastLine, FirstChar, LastChar :integer;

  function CompareChar(A,B :Char);
  begin
    Result := (A = B) or ((not CaseSensitive) and (UpCase(A) = UpCase(B)));
  end;

  function FindFirstMatch(var i :integer;
                          var j :integer;
                          var EndOfStrings :boolean)  :boolean;
    begin
      EndOfStrings := false;
      Found := false;
      while (not Found) and (not EndOfStrings) do begin
        if CompareChar(S[i][j], OldStr[1]) then Found := true
        else begin
          j := j + 1;
          if j > Length(S[i]) then begin
            i := i + 1;
            j := 1;
          end;
          if i > S.Count - 1 then EndOfStrings := true;
        end;
      if Found = true then begin
        FirstLine := i;
        FirstChar := j;
      end
      if EndOfStrings then Found := false;
      Result := Found;
    end;

  function CompareString(var i :integer;
                         var j :integer;
                         var EndOfStrings :boolean) :boolean;
    var k :integer;
        FoundEnd :boolean;
    begin
      k := 1;
      FoundEnd := true;
      while (k < Length(OldStr)) and (not EndOfStrings) do begin
        k := k + 1;
        j := j + 1;
        if j > Length(S[i]) then begin
          i := i + 1;
          j := 1;
        end;
        if i > S.Count - 1 then EndOfStrings := true;
        if EndOfStrings or (not CompareChar(S[i][j], OldStr[k])) then
          FoundEnd := false;
      end;
      if FoundEnd then begin
        LastLine := i;
        LastChar := j;
        EndOfStrings := False;
      end
      Result := FoundEnd;
    end;

var i,j :integer;
    FoundStart, FoundEnd, EndOfStrings :boolean;

begin
  i := 0;
  j := 1;
  repeat
    FoundEnd := False;
    FoundStart := FindFirstMatch(i, j, EndOfStrings);
    if not EndOfStrings then begin
      if FoundStart then FoundEnd := CompareString(i, j, EndOfStrings);
      if not FoundEnd then FoundStart := false;
    end;
  until FoundEnd or EndOfStrings;
  if FoundEnd then begin
    NewStrFirst := copy(S[FirstLine], 1, FirstChar) + NewStr;
    NewStrLast := copy(S[LastLine], LastChar, Length(S[LastLine]));
    S[FirstLine] := NewStrFirst;
    S[LastLine] := NewStrLast;
    if LastLine > (FirstLine + 1) then begin
      for c := (FirstLine + 1) to (LastLine - 1) do S.Delete(c);
  end;

end;

-----------------------------



Load your text file into a TMemo (I think it can be done using TMemo.Lines.LoadFromFile, but I'm not actually sure).

Send the string list to the function like this:

Replace(Memo.Lines, OldString, NewString, CaseSensitive)

where CaseSensitive is a boolean and Memo is the TMemo you are sending.  

This function can search and replace a new string over an old string that covers more than one line in the memo.

I wrote this, but did not compile and test it.  To do that would require me to build an application that would use it.  In order for me to do that it would take more than 50 points.

You could insert this into your source code (watch out for compiler errors), or better yet look it at to find out how it works.

Scrappy
0
 

Expert Comment

by:belgianbasman
ID: 1340911
A better solution would be ...

procedure Replace(orig, new, FileName : String);
begin
   Memo1:=TMemo.Create(nil);
   try
      begin
          Memo1.Lines.LoadFromFile(FileName);
          x:=Memo1.Text;
          while (pos(orig,x)>0) do
             begin
               x:=copy(x,1,pos(orig,x)-1) + new + copy(x,pos(orig,x)+length(orig)+1,length(x));
             end;                     {while ...}
          Memo1.Text:=x;
       end;                             {try ...}
   Finally
      begin
         Memo1.Lines.SaveToFile(<FileName);
         Memo1.Free;
      end;                 {finally...}
    END;                 {try...finally...}
end;


This works fine as long as the string to be replaced is not a part of the string to replace it with.  For that, I would have to design an algorithm a little bit more complicated.

Hope this helps....

cheers,

Basman
0

Featured Post

Live: Real-Time Solutions, Start Here

Receive instant 1:1 support from technology experts, using our real-time conversation and whiteboard interface. Your first 5 minutes are always free.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article explains how to create forms/units independent of other forms/units object names in a delphi project. Have you ever created a form for user input in a Delphi project and then had the need to have that same form in a other Delphi proj…
Objective: - This article will help user in how to convert their numeric value become words. How to use 1. You can copy this code in your Unit as function 2. than you can perform your function by type this code The Code   (CODE) The Im…
This Micro Tutorial hows how you can integrate  Mac OSX to a Windows Active Directory Domain. Apple has made it easy to allow users to bind their macs to a windows domain with relative ease. The following video show how to bind OSX Mavericks to …
Finds all prime numbers in a range requested and places them in a public primes() array. I've demostrated a template size of 30 (2 * 3 * 5) but larger templates can be built such 210  (2 * 3 * 5 * 7) or 2310  (2 * 3 * 5 * 7 * 11). The larger templa…

776 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question