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 个评论
Gabriel
Gabriel 2015-8-26
Hi, I don't have an example with me right now, but I will try to get one asap.
As I said, I need to replace a number (varying from 0.0 to 1.0) which is somewhere in a long txt file with numbers (also varying from 0.0 to 1.0) which are in another txt file but with a differente format
Cedric
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
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.

类别

Help CenterFile Exchange 中查找有关 Characters and Strings 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by