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!