How to replace and delete specific lines of a .txt file?

6 visualizaciones (últimos 30 días)
Ivan Mich
Ivan Mich el 1 de Abr. de 2023
Respondida: Atsushi Ueno el 1 de Abr. de 2023
Hello,
I have a question about a code. I have two .txt files with 15 columns (let's call them fileA.txt & fileB.txt). I would like to delete the rows (lines) from fileB.txt whose columns 3,4,6 are contained (are the same) in fileA.txt.
I mean that
fileA.txt contains:
5 6 7 8 10 Italy 18 22
4 3 2 1 5 Rome 22 38
11 26 17 1 93 Spain 40 85
and fileB.txt contains:
4 3 7 8 6 Italy 26 12
7 9 2 1 7 Rome 36 85
25 12 94 6 8 Turkey 23 78
after this process I would like to have these modifications:
fileA.txt
4 3 7 8 6 Italy 26 12
7 9 2 1 7 Rome 36 85
11 26 17 1 93 Spain 40 85
fileB.txt
25 12 94 6 8 Turkey 23 78
I think I should use commands isequal & ismember but I am condused. I am uploading the files..
Could you please help me?

Respuestas (1)

Atsushi Ueno
Atsushi Ueno el 1 de Abr. de 2023
ismember function works for your purpose.
fileA = readtable('https://jp.mathworks.com/matlabcentral/answers/uploaded_files/1342194/fileA.txt');
fileB = readtable('https://jp.mathworks.com/matlabcentral/answers/uploaded_files/1342199/fileB.txt');
result = ismember(fileB(:,[3 4 6]),fileA(:,[3 4 6]),'rows');
fileA(result,:) = fileB(result,:);
fileB(result,:) = [];
writetable(fileA,'fileA.txt','Delimiter','\t','WriteVariableNames',false);
writetable(fileB,'fileB.txt','Delimiter','\t','WriteVariableNames',false);
type fileA.txt
4 3 7 8 6 Italy 26 12 7 9 2 1 7 Rome 36 85 11 26 17 1 93 Spain 40 85
type fileB.txt
25 12 94 6 8 Turkey 23 78

Categorías

Más información sobre Characters and Strings en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by