替换文本文件中的特定行

Replace specific line in a text file

我有一个如下图所示的文本文件(例如:data.dat),有很多行。

data.dat

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

@controls
act= 2,3,4,5

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

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);

但这只是删除了原来的行!

非常感谢你的帮助。提前致谢。

如果您不受这种逐行方法的约束,例如,也可以使用 fileread and regexp 获取文件的所有行,修改它们,最后将它们保存回来归档。

这将是我的解决方案:

% 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 ';

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

希望对您有所帮助!

刚弄明白

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);