How to read strings and numbers in a text file?

1 回表示 (過去 30 日間)
Ravindu Lokuliyana
Ravindu Lokuliyana 2018 年 11 月 15 日
コメント済み: Ravindu Lokuliyana 2018 年 11 月 19 日
Hi there,
I got an attached type text file which needs to read the content, set them into variables and rewrite the text file again.
E.g. read 'A' in the text file as a variable and change its value into '2' and rewrite the text file. Same procedure should conduct to B,C,Trail01 and Trial02.
Can anyone help me to solve the problem using this example file?
  2 件のコメント
jonas
jonas 2018 年 11 月 15 日
You should probably use regexprep, but I don't understand what you are trying to do. Can you upload a "solution" that you've formatted manually?
Ravindu Lokuliyana
Ravindu Lokuliyana 2018 年 11 月 16 日
編集済み: Ravindu Lokuliyana 2018 年 11 月 16 日
Thank you very much for early response.
I got a text file with different variables which needs to run in an another programme (SWAN wave model) using command promt. The text file has lots of parameters and format can be simplified as follows.
SET LEVEL 0.0 % This controls the water level of the model
SET NOR 90.0 % This controls the direction
SET RHO 1025.0 % This controls the density of the water
Likewise there are lots of parameters. I need to read them in Matlab, set them into variables, change the value and save into different text files.
As an example,let's say I have a text file 'Test01.txt' and l need read the water level(LEVEL), set the LEVEL into 5.0, save into different text file ('Test02.txt'), and run the model using 'dos swanrun Test02' command in Matlab. Similarly I need to set different values to each parameter and run the model again and again.
I hope you can understand my problem and hereby attached the part of the original file.
Thank you.

サインインしてコメントする。

採用された回答

Jan
Jan 2018 年 11 月 16 日
編集済み: Jan 2018 年 11 月 16 日
% Import the file:
key = 'SET LEVEL';
new = 5.0;
file = 'Test01.txt'
cstr = strsplit(fileread(file), '\n');
% Find and replace the wanted line:
match = strncmpi(cstr, key, length(key));
cstr{match} = sprintf('%s %g', key, new);
% Write the file:
[fid, msg] = fopen(file, 'w');
if fid == -1, error('%s', msg); end
fprintf(fid, '%s\n', cstr{:});
fclose(fid);
The part "Same procedure should conduct to B,C,Trail01 and Trial02" is not clear to me, but it should not be hard to modify the above code to your needs.
  1 件のコメント
Ravindu Lokuliyana
Ravindu Lokuliyana 2018 年 11 月 19 日
It works fine. Thanks a lot!!!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeText Data Preparation についてさらに検索

タグ

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by