【问题标题】:Opening text file and replacing two strings in Matlab在 Matlab 中打开文本文件并替换两个字符串
【发布时间】:2019-11-22 09:36:03
【问题描述】:

我需要替换文本文件中的两个单独的字符串,然后将更改后的版本保存为新的文本文件。

到目前为止,我有以下代码:

fid = fopen('original_file.txt','rt') ;
X = fread(fid) ;
fclose(fid) ;
X = char(X.') ;

Y = strrep(X, 'results1.csv', 'results2.csv') ;
Z = strrep(X, 'plot1', 'plot2') ;
fid2 = fopen('new_file.txt','wt') ;
fwrite(fid2,Y) ;
fwrite(fid2,Z) ;

fclose (fid2) ;

此代码的问题在于它只是将文本文件的长度加倍 - 换句话说,new_file.txt 的行数是original_file.txt 的两倍。

首先写入的内容将results1.csv更改为results2.csv,然后将相同的内容附加plot1更改为plot2

有人可以指出我在这里缺少什么吗?

【问题讨论】:

    标签: string matlab file text


    【解决方案1】:

    问题是您正在创建两个变量YZ 并将这两个变量写入new_file.txt。要替换两个单独的字符串,请使用 strrep 函数两次:

    fid = fopen('original_file.txt','rt') ;
    X = fread(fid) ;
    fclose(fid) ;
    X = char(X.') ;
    
    Y = strrep(X, 'results1.csv', 'results2.csv') ;
    Z = strrep(Y, 'plot1', 'plot2') ; % replace the second string, after the first replacement
    fid2 = fopen('new_file.txt','wt') ;
    fwrite(fid2,Z) ; % write just Z, with both replacements
    
    fclose (fid2) ;
    

    【讨论】:

      猜你喜欢
      • 2019-10-01
      • 2016-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-31
      相关资源
      最近更新 更多