Reading .txt files and replace lines from one file to another
4 views (last 30 days)
Show older comments
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 Comments
Answers (1)
Walter Roberson
on 7 Apr 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 Comments
Walter Roberson
on 19 Apr 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()
See Also
Categories
Find more on String in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!