How can I edit a value in multiple text files?
조회 수: 6 (최근 30일)
이전 댓글 표시
I need to reduce the wave height (Hm0) values by 20% in 91 JONSWAP files that are named jonswap_#.inp. I attached two of them. I would appreciate your help with the code, thank you!
댓글 수: 2
답변 (2개)
Zhangxi Feng
2019년 10월 24일
A simple way to do this is to simply write the entire file, I assume it is not a large file.
You can do something like this:
function write(fname,input)
fileID = fopen(fname,'w');
fprintf(fileID,'Hm0\t= %5.1f\n',input(1));
fprintf(fileID,'fp\t= %5.1f\n',input(2));
...
You get the idea
댓글 수: 3
Zhangxi Feng
2019년 10월 24일
편집: Zhangxi Feng
2019년 10월 24일
You mean the 91 files have different parameters with different numbers?
You can read in the file as a whole, change the first line, then write the whole file back out.
Something like:
file = fileread('New.inp');
fileText = regexp(file, '\r\n|\r|\n', 'split')';
fileText{1}(15:end) = num2str(0.98);
fid = fopen('New.inp','w');
for i = 1:length(fileText)
fprintf(fid,[fileText{i},'\n']);
end
fclose(fid);
Note regexp will have issues if you try to use this across platforms. It works fine on Windows but may have issues on Linux. You can always read the file in using fgetl, I use regexp for less coding.
Akira Agata
2019년 10월 25일
I believe it's better to keep the original files and save the revised files to a different folder.
How about the following?
In this code, original .inp files are assumed to be stored in \Data1 folder, and revised .inp files will be saved to \Data2 folder.
fileList = dir(fullfile(pwd,'Data1','*.inp'));
for kk = 1:numel(fileList)
readFilePath = fullfile(fileList(kk).folder, fileList(kk).name);
C = readcell(readFilePath,'FileType','text');
C{1,3} = C{1,3}*0.8;
writeFilePath = fullfile(pwd,'Data2',fileList(kk).name);
writecell(C,writeFilePath,'FileType','text','Delimiter','\t');
end
댓글 수: 3
Akira Agata
2019년 10월 28일
readcell function is introduced in R2019a, so the code should be revised for R2018b or older version. Could you tell us your MATLAB version?
참고 항목
카테고리
Help Center 및 File Exchange에서 Data Type Conversion에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!