Файл a.txt
содержит около 100 тыс. Слов, каждое слово находится в новой строке
july.cpp
windows.exe
ttm.rar
document.zip
Файл b.txt
содержит 150 тыс. Слов, одно слово за строкой - некоторые слова из файла a.txt
, но некоторые слова являются новыми:
july.cpp
NOVEMBER.txt
windows.exe
ttm.rar
document.zip
diary.txt
Как я могу объединить эти файлы в одну, удалить все повторяющиеся строки и сохранить новые строки (строки, которые существуют в a.txt
, но не существуют в b.txt
] и наоборот)?
Существует команда, чтобы сделать это: comm
. Как указано в man comm
, это просто простой:
comm -3 file1 file2
Print lines in file1 not in file2, and vice versa.
Примечание, которое comm
ожидает, что содержание файлов будет отсортировано, таким образом, необходимо будет отсортировать их прежде, чем звонить comm
на них, точно так же, как это:
sort unsorted-file.txt > sorted-file.txt
Так для подведения:
sort a.txt > as.txt
sort b.txt > bs.txt
comm -3 as.txt bs.txt > result.txt
После выше команд, Вы будете ожидать строки в result.txt
файл.
Вот короткий python3 сценарий, на основе ответ Germar , который должен выполнить это при сохранении b.txt
неотсортированный порядок.
#!/usr/bin/python3
with open('a.txt', 'r') as afile:
a = set(line.rstrip('\n') for line in afile)
with open('b.txt', 'r') as bfile:
for line in bfile:
line = line.rstrip('\n')
if line not in a:
print(line)
# Uncomment the following if you also want to remove duplicates:
# a.add(line)
#!/usr/bin/env python3
with open('a.txt', 'r') as f:
a_txt = f.read()
a = a_txt.split('\n')
del(a_txt)
with open('b.txt', 'r') as f:
while True:
b = f.readline().strip('\n ')
if not len(b):
break
if not b in a:
print(b)
Взгляните на команду coreutils comm
- man comm
NAME
comm - compare two sorted files line by line
SYNOPSIS
comm [OPTION]... FILE1 FILE2
DESCRIPTION
Compare sorted files FILE1 and FILE2 line by line.
With no options, produce three-column output. Column one contains
lines unique to FILE1, column two contains lines unique to FILE2, and
column three contains lines common to both files.
-1 suppress column 1 (lines unique to FILE1)
-2 suppress column 2 (lines unique to FILE2)
-3 suppress column 3 (lines that appear in both files)
Так, например, можно сделать
$ comm -13 <(sort a.txt) <(sort b.txt)
diary.txt
NOVEMBER.txt
(строки, уникальные для b.txt
)