【问题标题】:Replace a string in a text file替换文本文件中的字符串
【发布时间】:2017-02-25 18:49:36
【问题描述】:

我想在 MATLAB 中替换文本文件中的字符串。

为了阅读指定的行,我使用了代码:

fid = fopen(file_name, 'r');
tt = textscan(fid, '%s', 1, 'delimiter', '\n', 'headerlines', i); 
ttt = str2num(tt{1}{1});

其中file_name 是我的文件名,ttt 是一个元胞数组,其中包含转换为整数的i-th 字符串。

例如,ttt = 1 2 3 4 5 6 7 8

现在,我想将 ttt 更改为 ttt = 0 0 0 0 0 0 0 0 并在文件的i-th 行写入新的ttt

有没有人想办法解决这个问题?

【问题讨论】:

    标签: string matlab text


    【解决方案1】:

    一个可能的实现是

    fid = fopen('input.txt', 'r+');
    tt = textscan(fid, '%s', 1, 'delimiter', '\n', 'headerlines', 1); % scan the second line
    tt = tt{1}{1};
    ttt = str2num(tt); %parse all the integers from the string
    ttt = ttt*0; %set all integers to zero
    
    fseek(fid, length(tt), 'bof'); %go back to the start of the parsed line
    format = repmat('%d ', 1, length(ttt));
    format = format(1:end-1); %remove the trailing space
    fprintf(fid, format, ttt); %overwrite the text in the file
    
    fclose(fid); %close the file
    

    这会将 input.txt 更改为:

    your first line
    1 2 3 4 5 6 7 8
    5 5 5 5 5 5 5 5
    

    进入

    your first line
    0 0 0 0 0 0 0 0 
    5 5 5 5 5 5 5 5
    

    请注意,只能覆盖文件中的现有字符。如果你想插入新字符,你有两个重写整个文件,或者至少从你想要插入新字符的位置开始。

    【讨论】:

      【解决方案2】:

      或者使用类似的东西...

      fid = fopen('input_file.txt', 'r');
      f = fread(fid, '*char')';
      fclose(fid);
       
      f = strrep(f, ' ', ''); % to remove
      f = strrep(f, ' ', ' .'); % to replace 
       
      % save into new txt file 
      fid = fopen('output_file.txt', 'w');
      fprintf(fid, '%s', f);
      fclose(fid);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-06-30
        • 2017-08-28
        • 1970-01-01
        • 2022-07-12
        • 1970-01-01
        • 2012-03-24
        • 1970-01-01
        相关资源
        最近更新 更多