How can I delete header from a .txt file and save it?
Mostrar comentarios más antiguos
I have a text file like this one:
element, unit, refTime, validTime, (62.000000,-6.250000)
HTSGW, [m], 197901010000, 197901010000, 0.000
HTSGW, [m], 197901010000, 197901010300, 0.220
HTSGW, [m], 197901010000, 197901010600, 0.420
HTSGW, [m], 197901010000, 197901010900, 0.560
HTSGW, [m], 197901010000, 197901011200, 2.190
I just want to remove the header and then save the file in the same .txt file without the header.
I may use the next script, shown in other forums, however I cannot save the generated list.
fid = fopen(Text);
tline = fgetl(fid);
tline = fgetl(fid);
while ischar(tline)
disp(tline)
tline = fgetl(fid);
end
fclose(fid);
I wish someone could help me. Thanks.
4 comentarios
Guillaume
el 1 de Jul. de 2016
The best way to not have to worry about windows or *nix, is to tell matlab to take care of line endings for you:
fopen(filename, 'rt'); %for reading
fopen(filename, 'wt'); %for writing
Guillaume
el 1 de Jul. de 2016
Ah yes, certainly it would be more efficient to do that outside of matlab with the OS tools (assuming there is one that does that, not sure about windows...).
Respuesta aceptada
Más respuestas (1)
Note: when using fopen always specify the permissions ('r' or 'w' mostly with optional 't' for text mode).
Your code only display the text. You also need to open a file for writing if you want to save it.
Probably the easiest way to do it all would be:
filecontent = fileread('somefile');
newcontent = regexp(filecontent, '(?<=[^\n\r].*[\n\r]+).*', 'match'); %keep everything but first line (defined as any number of characters but newline or carriage return followed by any number of newlines or carriage returns
fid = fopen('newfile', 'w');
fprintf(fid, '%s', newcontent);
fclose(fid);
2 comentarios
Javier Martinez
el 1 de Jul. de 2016
Guillaume
el 1 de Jul. de 2016
D'oh! either add , 'once' after the 'match' in the regexp call. or simply dereference the cell as it should only have one element:
fprintf(fid, '%s', newcontent{1});
Adding 'once' would be more correct.
Categorías
Más información sobre Large Files and Big Data en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!