Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Find and replace text in .txt file??

Posted on 1998-09-26
6
Medium Priority
?
190 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 

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 150 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

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Hello everybody This Article will show you how to validate number with TEdit control, What's the TEdit control? TEdit is a standard Windows edit control on a form, it allows to user to write, read and copy/paste single line of text. Usua…
Introduction I have seen many questions in this Delphi topic area where queries in threads are needed or suggested. I know bumped into a similar need. This article will address some of the concepts when dealing with a multithreaded delphi database…
In this video, Percona Director of Solution Engineering Jon Tobin discusses the function and features of Percona Server for MongoDB. How Percona can help Percona can help you determine if Percona Server for MongoDB is the right solution for …
We’ve all felt that sense of false security before—locking down external access to a database or component and feeling like we’ve done all we need to do to secure company data. But that feeling is fleeting. Attacks these days can happen in many w…
Suggested Courses

721 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