Add new line in middle of line of a text file
3 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
I have a bug in my text file. There should be new line at this blue line:
I have tried to code to fix this:
subdir = 'TCLFiles';
filename = 'Sections.tcl';
str = deblank(fileread(fullfile(pwd,subdir,filename)));
[oldhash,nonhash] = regexp(str,'\#','match','split');
nonhash = nonhash(2:end);
newtext = cell(1,length(oldhash));
for i=1:length(oldhash)
newtext{i} = sprintf('\n%s%s',oldhash{i},nonhash{i});
end
fid = fopen(fullfile(pwd,subdir,'Sections_fixed.tcl'),'wt');
fprintf(fid,'%s',newtext{:});
fclose(fid);
It works, but it creates many other unnecessary new lines. The result is quite a mess:
Its hard to understand these working-with-text. Any suggestion how to do it properly?
I attach the text file also if you need to take a look. Thank you.
0 comentarios
Respuestas (1)
Voss
el 3 de En. de 2024
unzip('Sections.zip')
% subdir = 'TCLFiles';
subdir = '';
oldfilename = fullfile(pwd,subdir,'Sections.tcl');
newfilename = fullfile(pwd,subdir,'Sections_fixed.tcl');
% original file contents, for reference
type(oldfilename)
% read the original file
str = fileread(oldfilename);
% replace any "#" that is not directly preceded by a newline character
% with a newline followed by a "#". that is, prepend a newline to any #
% that doesn't already have one
str = regexprep(str,'[^\n]#','\n#');
% write the new file
fid = fopen(newfilename,'wt');
fprintf(fid,'%s',str);
fclose(fid);
% check the new file contents (scroll down to see the whole thing)
type(newfilename)
0 comentarios
Ver también
Categorías
Más información sobre Environment and Settings en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!