替换文本文件中的特定行

时间:2019-10-24 21:50:11

标签: matlab file text text-files

我有一个文本文件(例如:data.dat),如下所示,其中包含多行。

data.dat

@motion parameters
speed= 22,30,60
range= 600
rotation= 50

@controls
act= 2,3,4,5

我想阅读并替换以特定关键字开头的行之后的行,例如“ @controls”。在这种情况下,要替换的行就是这一行:

act= 2,3,4,5

,应循环更改。例如,在瞬间,它将变为:

act= 1,0,8,-2

我已经尝试过

fullFileName = fullfile(pwd, 'data.dat')
% Open the file.
fileID = fopen(fullFileName, 'rt');
% Read the first line of the file.
textLine = fgetl(fileID);
while ischar(textLine)
  % Read the remaining lines of the file.
    fprintf('%s\n', textLine)
  if startsWith(textLine,'@controls')
    % Line starts with @controls, so change values
      textLine = fgetl(fileID); % Step one line below
      textLine = 'act= %4.1f,%4.1f,%4.1f,%4.1f\n ';
     fprintf(fileID,textLine,act_1,act_2,act_3,act_4);

  end
  % Read the next line.
    textLine = fgetl(fileID);
end
% All done reading all lines, so close the file.
fclose(fileID);

但这只会删除原始行!

感谢您的帮助。预先感谢。

2 个答案:

答案 0 :(得分:1)

如果您不受限于这种逐行方法,则可以(例如)还使用filereadregexp来获取文件的所有行,对其进行修改并最后将它们保存回文件。

这将是我的解决方案:

% Read whole content of file as text
C = fileread('data.dat');

% Split at every new line character; Caveat: Windows vs. Unix vs. MacOS
C = regexp(C, '\r\n', 'split').'

% Find line numbers of @controls lines
idx = find(strcmp('@controls', C))

% Replace following lines with desired values
act = [1, 0, 8, -2; 0, 1, 2, 3];
for id = 1:numel(idx)
  C{idx(id)+1} = sprintf('act= %d,%d,%d,%d', act(id, :));  
end
C

% Save file
fid = fopen('data.dat', 'r+');
fprintf(fid, '%s\r\n', C{:});
fclose(fid);

我这样使用了经过修改的data.dat

@motion parameters
speed= 22,30,60
range= 600
rotation= 50

@controls
act= 2,3,4,5

@controls
act= 2,3,4,5

执行上述脚本后,结果如下:

@motion parameters
speed= 22,30,60
range= 600
rotation= 50

@controls
act= 1,0,8,-2

@controls
act= 0,1,2,3

在您的问题中,您将所需的输出描述为:

act= 1,0,8,-2

但是,在您的代码中您拥有

textLine = 'act= %4.1f,%4.1f,%4.1f,%4.1f\n ';

因此,如有必要,请根据您的实际需求调整格式说明符。

希望有帮助!

答案 1 :(得分:0)

我刚刚弄清楚了。

fid = fopen('data.dat','r');        % Open File to read
replaceline = 'act= 1,0,8,-2';      % Line to replace
i = 1;
tline = 's';
A = {[]};
while ischar(tline)
    tline = fgetl(fid);
    if ~isempty(strfind(tline,'@controls')) % find '@controls'
        A{i}=tline;
        A{i+1} = replaceline;               % replace line
        tline = fgetl(fid);
        i = i+1;
    else
        A{i}=tline;
    end
    i = i+1;
end
fclose(fid);
fid2=fopen('data.dat','w');            % Open file to write
for i=1:length(A)-1
    fprintf(fid2,['%s',char([13,10])],A{i});
end
fclose(fid2);
相关问题