How can I edit a value in multiple text files?
4 次查看(过去 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!