how to replace a specific line in a text file with user data?

3 次查看(过去 30 天)
clear
Messege = 'Hello';
fileID = fopen('SampleFile.txt', 'rt');
textLine = fgetl(fileID);
lineCounter = 1;
while ischar(textLine)
fprintf('%s\n', textLine)
if startsWith(textLine, 'second line')
textLine = Messege % i want to replace this line with messege
disp('Done')
break
end
textLine = fgetl(fileID);
lineCounter = lineCounter + 1;
end
fclose(fileID);
my sample file contains three line data only "first line" "second line" "third line"... i want to replace my hello messge with line starts with string "second line".. code is running fine and display msg 'done' but gives error on messge line
>> Unable to perform assignmentbecause brace indexing is not supported for variable of this type <<
  2 个评论
Les Beckham
Les Beckham 2023-10-30
When I run your code I see no errors. It is not clear what you are really trying to do. Do you wish to change the contents of the file on disk?
Messege = 'Hello';
fileID = fopen('SampleFile.txt', 'rt');
textLine = fgetl(fileID);
lineCounter = 1;
while ischar(textLine)
fprintf('%s\n', textLine)
if startsWith(textLine, 'second line')
textLine = Messege % i want to replace this line with messege
disp('Done')
break
end
textLine = fgetl(fileID);
lineCounter = lineCounter + 1;
end
first line second line
textLine = 'Hello'
Done
fclose(fileID);
taimour sadiq
taimour sadiq 2023-10-30
yes i wish to change the contents of the file on disk... Voss Code Works Fine

请先登录,再进行评论。

采纳的回答

Voss
Voss 2023-10-30
input_file = 'SampleFile.txt';
output_file = 'SampleFile_modified.txt';
dbtype(input_file)
1 first line 2 second line 3 third line
Messege = 'Hello';
old_messege = 'second line';
L = readlines(input_file);
L(startsWith(L,old_messege)) = Messege;
writelines(L,output_file);
dbtype(output_file)
1 first line 2 Hello 3 third line
  3 个评论
Walter Roberson
Walter Roberson 2023-11-2
input_file = 'SampleFile.txt';
output_file = 'SampleFile_modified.txt';
dbtype(input_file)
1 first line 2 second line 3 third line
Messege = 'Hello';
old_messege = 'second line';
L = string(regexp(fileread(input_file), '\r?\n', 'split'));
L(startsWith(L,old_messege)) = Messege;
[fid, msg] = fopen(output_file, 'w');
if fid < 0
error('failed to open output file "%s" because "%s"', output_file, msg);
end
fwrite(fid, strjoin(L, newline));
fclose(fid)
ans = 0
dbtype(output_file)
1 first line 2 Hello 3 third line

请先登录,再进行评论。

更多回答(0 个)

产品


版本

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by