Solved

Find and replace text in .txt file??

Posted on 1998-09-26
6
181 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
Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

 

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

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Suggested Solutions

The uses clause is one of those things that just tends to grow and grow. Most of the time this is in the main form, as it's from this form that all others are called. If you have a big application (including many forms), the uses clause in the in…
Creating an auto free TStringList The TStringList is a basic and frequently used object in Delphi. On many occasions, you may want to create a temporary list, process some items in the list and be done with the list. In such cases, you have to…
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, Just open a new email message.  In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…
This video gives you a great overview about bandwidth monitoring with SNMP and WMI with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're looking for how to monitor bandwidth using netflow or packet s…

744 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

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now