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

14 次查看(过去 30 天)
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 个评论
Geoff Hayes
Geoff Hayes 2020-4-5
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 2020-4-5
编辑:Geoff Hayes 2020-4-5
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

请先登录,再进行评论。

采纳的回答

Geoff Hayes
Geoff Hayes 2020-4-5
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 个评论
Geoff Hayes
Geoff Hayes 2020-4-6
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 2020-4-6
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 个)

类别

Help CenterFile Exchange 中查找有关 Search Path 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by