How can I edit a value in multiple text files?
4 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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 Commenti
Risposte (2)
Zhangxi Feng
il 24 Ott 2019
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 Commenti
Zhangxi Feng
il 24 Ott 2019
Modificato: Zhangxi Feng
il 24 Ott 2019
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
il 25 Ott 2019
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 Commenti
Akira Agata
il 28 Ott 2019
readcell function is introduced in R2019a, so the code should be revised for R2018b or older version. Could you tell us your MATLAB version?
Vedere anche
Categorie
Scopri di più su Data Type Conversion in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!