Reading .txt files and replace lines from one file to another

4 views (last 30 days)
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.

Answers (1)

Walter Roberson
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
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()
Ivan Mich
Ivan Mich on 20 Apr 2020
Edited: Ivan Mich on 20 Apr 2020
I have written this code but I can not find the in order to run once for the first line of 2nd and 3rd column of File3 and execute the .exe, once for the second line of 2nd and 3rd columns and execute the .exe etc.
for i=1:size(t3,1)
replaced_lines = [e(1:36);k;e(38:67);M(1:1);e(69:116);tr;ex(118:178);(t3(i,:)); e(180)]
fid = fopen('file2.txt', 'wt');
fprintf(fid, '%s\n', replaced_lines{:});
fclose(fid)
system('my.exe<file2.txt')
end

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!