• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 192
  • Last Modified:

Find and replace text in .txt file??

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
summerset
Asked:
summerset
1 Solution
 
viktornetCommented:
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
 
summersetAuthor Commented:
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
 
elkiorsCommented:
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
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
summersetAuthor Commented:
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
 
scrapdogCommented:
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
 
belgianbasmanCommented:
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

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now