Reputation: 50
So line containing 'NVMEM' successfully deletes from the textfile. I actually want the opposite to happen where it will delete every line apart from the line containing the string 'NVMEM'. I tried changing the if statement under button 2's for loop, to an if not statement thinking that would work but it just deletes everything. Is there a way for me to be able to delete all of the lines apart from the one containing the stringy string.
implementation
{$R *.dfm}
procedure TForm3.Button1Click(Sender: TObject);
var
NVE: TextFile;
begin
if not FileExists('NVE.txt') then
begin
AssignFile(NVE, 'NVE.txt');
Rewrite(NVE);
WriteLn(NVE, 'abcdefg') ;
WriteLn(NVE, 'hijklmnop') ;
WriteLn(NVE, 'fmdiomfsa');
WriteLn(NVE, 'heres the line with NVMEM'); //line I want to parse
ShowMessage('You have successfully created the file amigo');
CloseFile(NVE);
end;
if FileExists('NVE.txt') then
begin
AssignFile(NVE,'NVE.txt');
Rewrite(NVE);
WriteLn(NVE, 'abcdefg') ;
WriteLn(NVE, 'hijklmnop');
WriteLn(NVE, 'hope i got that right');
WriteLn(NVE, 'heres the line with NVMEM'); //line I want to parse
ShowMessage('Eso Final');
CloseFile(NVE);
end;
end;
procedure TForm3.Button2Click(Sender: TObject);
var
NVE: string;
i : integer;
raw_data1,stringy: string;
raw_data: TstringList;
begin
stringy := 'NVMEM';
i := 0;
raw_data := TStringlist.Create;
try
raw_data.LoadFromFile('NVE.txt');
for i := raw_data.Count-1 downto 0 do
if pos(stringy, raw_data[i])<>0 then
raw_data.Delete(i);
raw_data.SaveToFile('NVE.txt');
finally
raw_data.free;
end;
end;
end.
Upvotes: 1
Views: 736
Reputation: 21045
First recall what function Pos(SubStr, Str: string): integer
does.
`Pos()` returns the position of `SubStr` within `Str` if `SubStr` is included in `Str`.
`Pos()` returns 0 when `SubStr` is not included in `Str`.
Now, to these lines of code in Button2Click()
(where i
is the index of a line in raw_data
) that you want to modify to delete all lines except the one that contains "NVMEM":
if pos(stringy, raw_data[i]) <> 0 then // your current code
raw_data.Delete(i);
Which can be spelled out as "if stringy is included in raw_data[i], then delete raw_data[i]" and which is opposite of what you want.
To turn the logic around, that is, "if stringy is not included in raw_data[i], then delete raw_data[i]", do as follows:
Pos()
returns 0 when SubStr
is not included in Str
, ergo, the condition for deleting a row should be:
if pos(stringy, raw_data[i]) = 0 then // change `<>` to `=`
raw_data.Delete(i);
That will leave you with one line left in the raw_data: TStringList
, the line that contains "NVMEM"
Upvotes: 1