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

15 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.
File1 has 2 columns with 3 lines, and File2 has 5 columns with 20 lines. I would like to read this files and after that I would like to take the two numbers of the first line of File1.txt and replace these two numbers to the column 3 and column 4 of the first line of the File2.txt.
I try to create a loop, but I can not understand how to create this code.
Could anyone help me?
  2 Comments
Geoff Hayes
Geoff Hayes on 5 Apr 2020
Ivan - please post the code that you have written so that we can help you understand what isn't working with the code.
Ivan Mich
Ivan Mich on 5 Apr 2020
Edited: Geoff Hayes on 5 Apr 2020
my code is incomplete because I don't understand how I can get specific data from the file so I'm confused.
clc
clear
file1=fileread('file1.txt')
file2=fileread('file2.txt')
filenameB = 'file2.txt';
outfilenameB = 'file2.txt';
LineToChange1 = 5;
NewContent1 = ' .....';
S = fileread(filenameB);
SS = regexp(S, '\r?\n', 'split');
SS{LineToChange1} = NewContent1;
fid = fopen(outfilenameB, 'w');
fprintf(fid, '%s\n', SS{:});
fclose(fid);
the point is that I would like to replace the values of 3rd nad 4th column of the first line of file2.txt (521 625 in file2.txt) with the values of the first line in file1.txt (6.4 30 in file1.txt). I think i should use a loop with for but i can not compose my code. I sent you these files for your facilitation.
Thank you in advance

Sign in to comment.

Accepted Answer

Geoff Hayes
Geoff Hayes on 5 Apr 2020
Ivan - try using importdata to read your text files, perhaps something like
file1Data = importdata('file1.txt', ' ', 1); % skip the header row
file2Data = importdata('file2.txt');
Now you have two matrices and so you should be able to access the appropriate rows of either to do whatever changes are necessary. You can then write out the results back to file with writematrix or equivalent.
  11 Comments
Geoff Hayes
Geoff Hayes on 6 Apr 2020
Is the line of File1.txt a string? Are the strings in each line of File2.txt the same length? Please illustrate with an example of what you want to do...
Ivan Mich
Ivan Mich on 6 Apr 2020
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.

Sign in to comment.

More Answers (0)

Categories

Find more on Search Path 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!