Replace specific line in a text file

40 ビュー (過去 30 日間)
Islam Elnady
Islam Elnady 2019 年 10 月 24 日
編集済み: Islam Elnady 2019 年 10 月 26 日
Hi everyone,
I have a text file (for example: data.dat) as shown below, with a number of lines.
data.dat
@motion parameters
speed= 22,30,60
range= 600
rotation= 50
@controls
act= 2,3,4,5
I want to read it and replace the line that comes right after the line starting with a specfic keyword e.g. "@controls" . In this case, the line to be replaced is this one
act= 2,3,4,5
and it should be changed in a loop. For an instant, for example, it would change to:
act= 1,0,8,-2
I'd appreciate your help. Thanks in advance.

採用された回答

Shubham Gupta
Shubham Gupta 2019 年 10 月 25 日
One of the way could be:
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);
Let me know if you have doubts !
  2 件のコメント
Islam Elnady
Islam Elnady 2019 年 10 月 26 日
編集済み: Islam Elnady 2019 年 10 月 26 日
Thank you for help. It worked perfect. But when I changed
A{i+1} = replaceline;
to
A{i} = replaceline;
So that I could replace the same line. If there is a line below the repleaced one, it'll be deleted and replaced with a blank line. What edits should be made to fix this?
Islam Elnady
Islam Elnady 2019 年 10 月 26 日
編集済み: Islam Elnady 2019 年 10 月 26 日
while ischar(tline)
tline = fgetl(fid);
if ~isempty(strfind(tline,'@controls')) % find '@controls'
A{i}=tline;
A{i} = replaceline; % replace line
% tline = fgetl(fid);
% i = i+1;
else
A{i}=tline;
end
i = i+1;
end
I figured it out. This will replace the same line that contains the pattern. Thank you again!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeText Data Preparation についてさらに検索

製品


リリース

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by