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!