Filter löschen
Filter löschen

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

3 Ansichten (letzte 30 Tage)
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 Kommentare
Les Beckham
Les Beckham am 30 Okt. 2023
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 am 30 Okt. 2023
yes i wish to change the contents of the file on disk... Voss Code Works Fine

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Voss
Voss am 30 Okt. 2023
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 Kommentare
Walter Roberson
Walter Roberson am 2 Nov. 2023
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

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Produkte


Version

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by