Replace data in a text file with data from another txt

4 ビュー (過去 30 日間)
Gabriel
Gabriel 2015 年 8 月 25 日
編集済み: Cedric 2015 年 8 月 26 日
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 Center および File ExchangeCharacters and Strings についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by