Effacer les filtres
Effacer les filtres

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

3 vues (au cours des 30 derniers jours)
taimour sadiq
taimour sadiq le 30 Oct 2023
Commenté : taimour sadiq le 2 Nov 2023
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 commentaires
Les Beckham
Les Beckham le 30 Oct 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 le 30 Oct 2023
yes i wish to change the contents of the file on disk... Voss Code Works Fine

Connectez-vous pour commenter.

Réponse acceptée

Voss
Voss le 30 Oct 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 commentaires
Walter Roberson
Walter Roberson le 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
taimour sadiq
taimour sadiq le 2 Nov 2023
Works Fine.. Thanks

Connectez-vous pour commenter.

Plus de réponses (0)

Produits


Version

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by