Matt Biggs
Matt Biggs

Reputation: 177

Search TextFile for Line with a specific string

Is it possible to search a TextFile line by line to find a specific string. ie. Hello It searches line by line to find if any line has Hello in it. There will only be one string per line. Is this possible? If so how do I attempt this?

Upvotes: 1

Views: 12740

Answers (2)

Blorgbeard
Blorgbeard

Reputation: 103437

An easy way is to use TStringList.LoadFromFile to load the file, then check IndexOf('hello') - if it's greater than -1, the string is in the file.

var
  sl : TStringList;
  ix : Integer;
begin
  sl := TStringList.Create;
  try      
    sl.LoadFromFile('test.txt'); 
    ix := sl.IndexOf('Hello');
    if ix > -1 then ShowMessage('Yup, the file contains a greeting.');
  finally 
    sl.Free;
  end;
end;

Upvotes: 1

David Heffernan
David Heffernan

Reputation: 612794

It's certainly easiest to load the entire file into memory. Provided that your file is small enough then you can do it like this:

found := false;
sl := TStringList.Create;
try
  sl.LoadFromFile(fileName);
  for line in sl do
    if Pos('Hello', line)<>0 then
    begin
      found := true;
      break;
    end;
finally
  sl.Free;
end;

I assume that when you say

if any line has Hello in it

that you are looking for lines that contain the search string rather than lines that equal the search string.


In a comment you ask:

Ok can I then ask if it would be possible to ask on how to delete a string that is typed from an edit box out of a file? So you enter a string into an edit box then it searches the file for it and deletes that line?

That's an easy enough variation of the above:

procedure RemoveLinesContaining(const fileName, searchText: string);
var
  sl: TStringList;
  i: Integer;
begin
  sl := TStringList.Create;
  try
    sl.LoadFromFile(fileName);
    for i := sl.Count-1 downto 0 do
      if Pos(searchText, sl[i])<>0 then
        sl.Delete(i);
    sl.SaveToFile(fileName);
  finally
    sl.Free;
  end;
end;

This function deletes all lines that contain the search string. If you only want to delete the first such line, then break out of the for loop after the call to Delete.

The loop variable is descending to allow the loop to modify the list.

If you want to use a different test, say equality rather than contains, then simply modify the if statement.

Upvotes: 8

Related Questions