Add new line in middle of line of a text file
5 次查看(过去 30 天)
显示 更早的评论
I have a bug in my text file. There should be new line at this blue line:
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/286847/image.jpeg)
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:
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/286848/image.jpeg)
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 个评论
回答(1 个)
Voss
2024-1-3
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Import and Export 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!