Replace data in a text file with data from another txt
4 ビュー (過去 30 日間)
古いコメントを表示
Hi, I need to replace data in some specific spots in a long text file with data from another .txt. More specifically, I have a .txt file which is a program for another software and some numbers are the inputs. I need to have the Matlab able to locate these exact points where are these inputs in the txt and replace them with inputs from another .txt file.
Thanks in Advance !
3 件のコメント
Cedric
2015 年 8 月 26 日
編集済み: Cedric
2015 年 8 月 26 日
We need to know exactly the content unless you want to operate on all numbers (strings that represent them). If you need to replace all '0.67' with '0.79' it is easy, you just do something like
content = fileread( 'MyData.txt' ) ;
content = strrep( content, '0.67', '0.79' ) ;
fId = fopen( 'MyData_updated.txt', 'w' ) ;
fwrite( fId, content ) ;
fclose( fId ) ;
but I suspect that you need to do more than that, or to perform updates at more specific locations. If you need to update
x = 0.6749 ;
and replace the number with '0.79', we need to see that it is only after a variable named 'x', that there can be more than one space after the equal sign, that numbers can have more digits than two after the decimal point, etc. If you/we are not specific enough, then there is a risk that replacements will occur at places where you don't want them. To illustrate, if you want to replace '1.0' in a statement like
x = 1.0 ;
and use a basic STRREP(content,'1.0','0.7') approach for this purpose, it will also perform replacements in e.g.
if y == 1.0 -> if y == 0.7
z = 1.0456 -> z = 0.7456
回答 (1 件)
Walter Roberson
2015 年 8 月 25 日
You need to read the old file and write a new file containing the updated content. It is not possible to update a text file "in the middle" -- not unless the updates are exactly the same size as the original data.
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Characters and Strings についてさらに検索
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!