How can i remove all spaces from all lines in a text file?

13 views (last 30 days)
In a text file i want to remove all spaces from all the lines to create a file with the same lines , but without the spaces

Answers (2)

the cyclist
the cyclist on 24 May 2016
Edited: the cyclist on 24 May 2016
Here is one way:
fid_in = fopen('text_in.txt');
fid_out = fopen('text_out.txt','w');
text_in = fgetl(fid_in);
while ischar(text_in)
text_out = [regexprep(text_in,' ','')];
fprintf(fid_out,'%s\n',text_out);
disp(text_in)
disp(text_out)
text_in = fgetl(fid_in);
end
fclose(fid_in);
fclose(fid_out);
I tested it on the attached file.

Stephen23
Stephen23 on 24 May 2016
Edited: Stephen23 on 24 May 2016
Here is a fast solution in just three lines:
>> fid = fopen('text_out.txt','wt');
>> fprintf(fid,'%s',strrep(fileread('text_in.txt'),' ',''))
>> fclose(fid);

Categories

Find more on MATLAB Report Generator 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!