Deleting several lines from text file (.txt)
2 次查看(过去 30 天)
显示 更早的评论
Hallo dear community,
for the moment I'm facing another problem after the solving the first one. I have a text file from a measurement instrument, and i want to load them into a cell array. reading the complete file is working. But there are several lines of blanks and not usable informations of sensors, wich doesn't need to be imported. Therefore I tried to write some primitive code to delete these cells afterwards from the ell array, but it seems not the logical way.
The formatting of the textfile can be found in attachment. The lines starting with ID 1 are usefull informations and need to be keept, lines with ID 2 doesn't need to be keept.
For reading out the complete file i used this code ( Sorry for the amaturistic way of coding, I'm just starting to learn all the Matlab coding :) ) :
function data = readAE(filename)
fid = fopen(filename,'r');
finallyClose = onCleanup(@()fclose(fid));
formatSpec = '%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%[^\n\r]';
delimiter = {' ',':'};
data = textscan(fid, formatSpec,'Delimiter',delimiter,'MultipleDelimsAsOne', true);
for iCol = 1:numel(data)
data{iCol} = cellfun(@(str) str2double(str) , data{iCol});
end
By doing so, my result is a 1x27 cell array. Now I tried to write a for loop to read out every line, compare the first value if it is 1 or not, and then copying the complete line of the cell array to a new text file, so a could keep only the useful informations.
The for loop lookes like this, but it's not working since I'm doing something wrong with the cell array:
fileID = fopen('results.txt','w');
for row = 1:numel(data{1})
if data{1}(row)==1
fprintf(fileID,formatSpec,data{row,:});
end
end
I thank you all very much for the support and help that I'm getting here !
0 个评论
采纳的回答
Stephen23
2016-7-11
If you only need to copy those lines form one file to another, then try something like this:
fid = fopen('test.txt','rt');
fin = fopen('test_new.txt','wt');
S = fgetl(fid);
while ischar(S)
if ~isempty(S) && strcmp(S(3),'1')
fprintf(fin,'%s\n',S);
end
S = fgetl(fid);
end
fclose(fid);
fclose(fin);
0 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Text Data Preparation 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!