Reputation: 527
To delete rows with a specified string, I read
http://www.mathworks.com/matlabcentral/answers/34567-remove-row-with-matching-string
I did but failed.
text.txt looks like
123 A omit B
2323 C omit D
333 oh
And I coded
fid = fopen('text.txt');
tttt = textscan(fid, '%s %s','delimiter','\t','HeaderLines',0)
tttt(strcmp(tttt{2}, 'omit'), :) = []
strcmp(tttt{2}, 'omit')
But MatLab showed me "Empty cell array: 0-by-3" and
ans =
0
0
0
I guess the type of file "tttt" is wrong (because I had to write "tttt{2}" rather than tttt(:,2)) but I am not sure.
Upvotes: 1
Views: 1678
Reputation: 3037
If performance is a concern, you might try invoking Unix's sed directly from within Matlab:
system('sed ''/omit/d'' text.txt > output.txt');
Here is the analogous command, calling AWK from within Matlab:
system('awk ''!/omit/'' text.txt > output.txt');
Upvotes: 1
Reputation: 38032
You are using strcmp()
, which compares the equality of two strings. That is not what you are after; you want to check whether some string is a substring of another string. You can use strfind
or findstr
or regexp
or regexprep
for that purpose.
ALso, you are not closing your text file. This can lead to all sorts of problems. Make it a habit to always write fid = fopen(...); fclose(fid);
as if it is one command, and then continue coding in between.
A small example:
fid = fopen('text.txt');
tttt = textscan(fid, '%s %s','delimiter','\t');
tttt{2}(~cellfun('isempty', strfind(tttt{2}, 'omit'))) = [];
fclose(fid);
EDIT: based on your comments, I think you want to do this:
fid = fopen('text.txt');
% Modified importcommand
tttt = textscan(fid, '%s%s',...
'delimiter','\t',....
'CollectOutput', true);
tttt = tttt{1};
% Find rows for deletion
inds = ~cellfun('isempty', strfind(tttt(:,2), 'omit'));
% aaaand...kill them!
tttt(inds,:) = [];
fclose(fid);
Upvotes: 3