How can I edit a value in multiple text files?
4 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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 comentarios
Bob Thompson
el 24 de Oct. de 2019
How much do you have written so far? How are you loading your files?
Respuestas (2)
Zhangxi Feng
el 24 de Oct. de 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 comentarios
Zhangxi Feng
el 24 de Oct. de 2019
Editada: Zhangxi Feng
el 24 de Oct. de 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
el 25 de Oct. de 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 comentarios
Akira Agata
el 28 de Oct. de 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?
Ver también
Categorías
Más información sobre Data Type Conversion en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!