How to delete lines in a text file?
24 views (last 30 days)
Show older comments
I have thousands of datafiles with headerlines and then 2 columns of data. For example:
mmmmmm_0001.chi
datatype measurement
units
comment
5.5993205E-01 0.0000000E+00
5.7147706E-01 0.0000000E+00
5.8302206E-01 0.0000000E+00
5.9456706E-01 0.0000000E+00
6.0611206E-01 5.9196600E+02
6.1765701E-01 5.9167889E+02
6.2920201E-01 5.9606128E+02
6.4074701E-01 6.1506769E+02
6.5229201E-01 6.2716541E+02
6.6383702E-01 6.3965259E+02
To import them in another software without errors I need to modify all the files keeping the first 4 rows of headerlines, and deleting only the first 4 lines of data (with intensity = 0). There is a way to do this with MATLAB? I cannot read from line 5 and append the headerlines later because they are changing for each file (...001.chi, ...002.chi and so on). The task is quite easy: I only need to delete an interval of lines (from line x to line y) and save the file, but I could not find any answer on the previous topics.
Edit: see attached file
0 Comments
Answers (1)
Stephen23
on 4 Jun 2015
Edited: Stephen23
on 6 Jun 2015
EDIT: now the the OP has actually posted a sample data file.
% Read file data into MATLAB:
fid = fopen('measur_xknh2%20(1-x)kh_x1_1.txt','rt');
hdr = textscan(fid,'%s',4,'Delimiter','\n','Whitespace','');
dat = cell2mat(textscan(fid,'%f%f'));
fclose(fid);
% Remove rows with zeros in the last column:
dat = dat(dat(:,2)>0,:);
% Save data in a new file:
fid = fopen('newfile.txt','wt');
fprintf(fid,'%s\n',hdr{1}{:});
fprintf(fid,' %.7E %.7E\n',dat.');
fclose(fid);
This code produces a copy of the original file, excluding the rows where the second column had value zero. To process a sequence of files you should read this:
0 Comments
See Also
Categories
Find more on Data Import and Export in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!