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

조회 수: 6 (최근 30일)
Ivan Mich
Ivan Mich 2023년 4월 1일
답변: Atsushi Ueno 2023년 4월 1일
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?

답변 (1개)

Atsushi Ueno
Atsushi Ueno 2023년 4월 1일
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

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by