Add new line in middle of line of a text file
3 views (last 30 days)
Show older comments
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 Comments
Answers (1)
Voss
on 3 Jan 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 Comments
See Also
Categories
Find more on Environment and Settings 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!