opening many files and changing code to match file name
조회 수: 1 (최근 30일)
이전 댓글 표시
Hello,
I was hoping that somebody might be able to help me with a problem that I have. I have 1000 files in the current directory called
RW1.a_process
RW2.a_process
RW3.a_process...
RW1000.a_process
I was wondering for each file how can I open it and change 2 lines in the code to be the same as the file name.
This file is called RW1.a_process
You will see RW1 in the two places marked red.
Is there anyway that I could do this for the remainder of the files? It would take me hours to do it manually.
Sincere thanks
John
댓글 수: 4
Rick Rosson
2012년 3월 18일
Are the two lines of text always lines 2 and 15, or do they change location from one file to the next?
채택된 답변
Jiro Doke
2012년 3월 18일
This is probably a little too specific to your case, i.e. it's looking for a particular text. I'm just using strrep but if it doesn't work, you may have to look at regexprep.
In general, I agree with Rick that you should do this from the beginning (using your original file), instead of creating 1000 copies, changing the file names, and then changing those 2 lines.
d = dir('*.a_process');
for id = 1:length(d)
[p, name] = fileparts(d(id).name);
fid = fopen(d(id).name, 'r');
str = textscan(fid, '%s', 'delimiter', '\n', 'whitespace', '');
fclose(fid);
% Replace Strings
newStr = strrep(str{1}, 'Run RW Cycle', ['Run ', name, ' Cycle']);
newStr = strrep(newStr, 'RW.mat', [name, '.mat']);
% Overwrite
fid = fopen(d(id).name, 'w');
fprintf(fid, '%s\n', newStr{:});
fclose(fid);
end
추가 답변 (1개)
Rick Rosson
2012년 3월 18일
It may be easier to delete all of the files except for the original source file, and then use MATLAB to create all of the copies for you, but with the two specific lines customized on each copy.
Maybe, for example:
for k = 2:1000
fileName = ['RW' num2str(k)];
source = fopen( 'RW1.a_process','r');
target = fopen([fileName '.a_process'],'w');
Ln = 0;
while ~feof(source)
Ln = Ln + 1;
aLine = fgetl(source);
if Ln == 2
aLine = sprintf(...);
else
if Ln == 15
aLine = sprintf(...);
end
end
fprintf(target,'%s\n',aLine);
end
fclose(target);
fclose(source);
end
I realize that this code is not optimized, but it may help as a starting point.
HTH.
Rick
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Startup and Shutdown에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!