How to find a specific string in a text file and delete that row?

Hi
I have text file that includes a register with personnumbers and names of peoples. I want to be able to edit that textfile by giving the code the name as a string input, and the code deletes the corresponding row to that name.
I have looked around, but I can't find any good example for this. Thank you for your help.
Regards

2 Kommentare

Cedric
Cedric am 19 Apr. 2013
Bearbeitet: Cedric am 19 Apr. 2013
How should be managed situations where multiple occurrences of a name exist in the file?
Maybe by giving both the first name and the surname, or by giving the personnumber as a string input.

Melden Sie sich an, um zu kommentieren.

 Akzeptierte Antwort

Image Analyst
Image Analyst am 19 Apr. 2013

0 Stimmen

Look at the help for fgetl(). Just open the file, read line by line, for each line, use strfind() or strcmpi() to check the line against your template, and if it's not the template, write it out to another file. Then you can delete the first file and rename the output file the same as your original input file. Come back with your code if you still have problems, but at least give it a try yourself - like I said, the help has sample code for you.

3 Kommentare

Hi,
Thank you for your help, but I'm new with matlab and I'm still struggeling a bit. This is what I've done so far:
clc; clear all;
name_delete = input('What name do you want to delete? \n','s');
fid=fopen('red4.txt');
while ~feof(fid)
tline = fgetl(fid);
IndexC = strfind(tline,name_delete)
%Here I want to make the expression that deletes the corresponding line%
end
fclose(fid);
Example of how the register looks like:
Cichowski, Thomas 720114
Bojang, Viktoria 681113
Lundgren, Michael 720310
Thanks in advance.
Which one is the line that you don't want? Did you see this in the help:
TF = strcmpi(string,string) comparestwo strings for equality, ignoring any differences in letter case.The strings are considered to be equal if the size and content ofeach are the same. The function returns a scalar logical 1 for equality,or scalar logical 0 for inequality.
So did you try something like
if ~strcmpi(tline, 'Cichowski, Thomas 720114')
% Write to output as long as it's not the bad line.
fprintf(fid_Output, '%s', tline);
end
I want to give a string as an input, and I want to delete the line where this string is a part of the line.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Hassan
Hassan am 19 Apr. 2013

1 Stimme

That helped alot.
Thank you so much for your help, I really appriciate it.
Regards

Kategorien

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by