Replace data in a text file with data from another txt

4 views (last 30 days)
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 Comments
Gabriel
Gabriel on 26 Aug 2015
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 on 26 Aug 2015
Edited: Cedric on 26 Aug 2015
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

Sign in to comment.

Answers (1)

Walter Roberson
Walter Roberson on 25 Aug 2015
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.

Categories

Find more on Characters and Strings in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!