Azzera filtri
Azzera filtri

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

3 visualizzazioni (ultimi 30 giorni)
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 Commenti
Les Beckham
Les Beckham il 30 Ott 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 il 30 Ott 2023
yes i wish to change the contents of the file on disk... Voss Code Works Fine

Accedi per commentare.

Risposta accettata

Voss
Voss il 30 Ott 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 Commenti
Walter Roberson
Walter Roberson il 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

Accedi per commentare.

Più risposte (0)

Prodotti


Release

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by