Reading .txt files and replace lines from one file to another
3 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Hello, I have a problem with a code.
First of all I have two .txt files, file1.txt and file2.txt. my problem is how to replace one line from one .txt with a line from another .txt file
I am uploading the two files in order to understand what I want to do. in these files, I would like to replace line 3 from File2 once with the first line of File1, once with the second line of file1 and once with the third line of File1.
I have to mention that i use readfile('File2.txt') in order to read this file.
0 commentaires
Réponses (1)
Walter Roberson
le 7 Avr 2020
lines1 = regexp(fileread('File1.txt'), '\r?\n', 'split');
lines2 = regexp(fileread('File2.txt'), '\r?\n', 'split');
replaced_lines = [lines2(1:2); lines1(2:4); lines2(3:end)];
fid = fopen('New_File2.txt', 'wt');
fprintf(fid, '%s\n', replaced_lines{:});
fclose(fid)
14 commentaires
Walter Roberson
le 19 Avr 2020
you have been shown all of tools you need. Splitting files into lines, selecting parts, replacing parts, creating output files from the modified versions.
When you system() out, you are always providing the same input file name in your i/o redirection. I do not know how you expect it to find the files you newly created. I think you need to construct the command that you pass to system()
Voir également
Catégories
En savoir plus sur String dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!