过去我曾多次在这里提出类似的问题,并取得了巨大的成功,但现在我的需求略有变化,我正在努力获得我正在寻找的确切输出。
我想比较2相似的分隔文件,但它们将具有不同的行数和一些重复项。这些文件将具有相同的标头。
file1.txt
mem_id date time building
aa1 bb1 cc1 dd1
aa2 bb2 cc2 dd2
aa3 bb3 ccx3 dd3
aa4 bb4 cc4 dd4
aa5 bb5 cc5 dd5
file2.txt
mem_id date time building
aa1 bby1 cc1 ddy1
aa2 bb2 cc2 dd2
aa3 bb3 cc3 dd3
aa4 bb4 cc4 dd4
aa4 bb4a cc4a dd4a
你会发现有 4 个不同点:
1- File2,mem_id aa1 在“日期”和“建筑物”列中都有“y”
2- File1,mem_id aa3 在“时间”列中有一个“x”
3- File1,有一个 mem_id aa5
4- File2,mem_id aa4 有 2 个条目
我想运行一个脚本来仅输出两个文件之间的差异(跳过相同的行)。我尝试过的所有内容都会挂在重复或跳过的行上,从而弄乱整个文件的输出。如果所有行都匹配,则以下代码可以正常运行:
current_code
awk -F ',' 'BEGIN {IGNORECASE = 1} NR==1 {for (i=1; i<=NF; i++) header[i] = $i}NR==FNR {for (i=1; i<=NF; i++) {A[i,NR] = $i} next}{ for (i=1; i<=NF; i++) if (A[i,FNR] != $i) print header[1]"#-"$1": " header[i] "- " ARGV[1] " value= ", A[i,FNR]" / " ARGV[2] " value= "$i}'
desired_output.txt
Mem_id#-aa1 : date- file1.txt value = bb1 / file2.txt value= bby1
Mem_id#-aa1 : building- file1.txt value = dd1 / file2.txt value= ddy1
Mem_id#-aa3 : time- file1.txt value = ccx3 / file2.txt value= dd3
Mem_id#-aa4 : date- file1.txt value = / file2.txt value= bb4a
Mem_id#-aa4 : time- file1.txt value = / file2.txt value= cc4a
Mem_id#-aa4 : building- file1.txt value = / file2.txt value= dd4a
Mem_id#-aa5 : date- file1.txt value = bb5 / file2.txt value=
Mem_id#-aa5 : time- file1.txt value = cc5 / file2.txt value=
Mem_id#-aa5 : building- file1.txt value = dd5 / file2.txt value=
答案1
以下 python 程序应该执行您想要的操作,或者非常接近它的操作。
第三行
desired_output.txt
似乎是错误的:Mem_id#-aa3 : time- file1.txt value = ccx3 / file2.txt value= dd3
cc3`
dd3 should probably be
除此之外,程序的输出除了空格之外都匹配,这在示例输出中似乎有点不规则。
输入被认为是按键(memid)排序的
- 程序在尝试同步时默认缓冲 4 行 (max_diff + 1)。如果该缓冲区中的键中没有一个与“当前”键匹配,则 vv 均被视为不匹配并打印,并尝试下一对。如果找到某个键,则将其他缓冲区中的不匹配项或首先输出。
当第一行和第二行具有相同的 memid 两次(或更多)时,示例输入对预期的行为有一些限制。
在
output()
我尝试匹配任何行并弹出所有匹配项(从左到右)。因此,同一 memid 中匹配行的顺序并不重要。如果左侧或右侧或两者都为空,则打印很容易(特别是当两者都为空时)。对于其余的,我从左到右匹配剩余的每一行。fmt
中的字符串决定line_out()
输出,您可以自由更改/重新排序。
#! /usr/bin/env python
# coding: utf-8
# http://unix.stackexchange.com/q/161913/33055
from __future__ import print_function
from collections import OrderedDict
from logging import debug
import sys
class RowBuffer:
def __init__(self, file_name, delim=None, max_diff=3):
"""delim is the character that is used for splitting input.
None->whitespace
"""
self._verbose = 0
self._file_name = file_name
self._fp = open(self._file_name)
self._delim = delim
self._max_diff = max_diff
self._head = self._fp.readline().split(delim)
# the buffer consists of a maximum of max_diff entries
# the keys are the first items of a row, the value a list
# of all other items on that row
self._buffer = OrderedDict()
self.fill_buffer()
def compare(self, rb):
"""check if self._buffer"""
if self._head != rb._head:
print('headings differ:\n {}\n {}'.format(
self._head, rb._head))
while self._buffer:
l = self.get()
try:
r = rb.get()
except KeyError:
debug('only left %s', l[0])
self.output(l, None, rb)
break
if l[0] == r[0]:
debug('compare vals %s', l[0])
self.output(l, r, rb)
continue
if l[0] in rb:
# left key in right, but not at top
# output right until top keys are same
while l[0] != r[0]:
debug('only right %s', r[0])
self.output(None, r, rb)
r = rb.get()
self.output(l, r, rb)
continue
if r[0] in self:
# right key in left, but not at top
# output left until top keys are same
while l[0] != r[0]:
debug('only left %s', l[0])
self.output(l, None, rb)
l = self.get()
self.output(l, r, rb)
continue
# neither found: output both
debug('neither left in right nor vv %s %s', l[0], r[0])
self.output(l, None, rb)
self.output(None, r, rb)
while rb._buffer: # remaining in right file
r = rb.get()
debug('only right %s', r[0])
self.output(None, r, rb)
def output(self, l, r, right):
fmt1 = '{col0_header}#-{col0_value} : {col_header}- ' \
'{left_file_name} value = {left_value} / ' \
'{right_file_name} value= {right_value}'
d = dict(
col0_header=self._head[0],
left_file_name=self._file_name,
right_file_name=right._file_name,
)
if l is not None and r is not None:
# one or more values on both sides, compare all lines on the
# left with all on the right remove any matching pairs
match = {} # left index to right index
for lidx, lv in enumerate(l[1]):
for ridx, rv in enumerate(r[1]):
if lv == rv:
if lidx not in match:
match[lidx] = ridx
# pop from back of list, not invalidate index
for lidx in sorted(match, reverse=True):
l[1].pop(lidx)
for ridx in sorted(match.values(), reverse=True):
r[1].pop(lidx)
if r is None or not r[1]:
for lv in l[1]:
for idx, k in enumerate(self._head[1:]):
self.line_out(d, col0_value=l[0], col_header=k,
left_value=lv[idx], right_value=' ')
return
if l is None or not l[1]:
for rv in r[1]:
for idx, k in enumerate(self._head[1:]):
self.line_out(d, col0_value=l[0], col_header=k,
left_value=' ', right_value=rv[idx])
return
# print non matching
for lv in l[1]:
for rv in r[1]:
for idx, k in enumerate(self._head[1:]):
if lv[idx] == rv[idx]:
continue # same value
self.line_out(d, col0_value=l[0], col_header=k,
left_value=lv[idx], right_value=rv[idx])
def line_out(self, d, **kw):
# manipulate and print output
# the fields of the format string can be arbitrarily arranged
# as long as the field names (between {} match)
fmt = '{col0_header}#-{col0_value} : {col_header}- ' \
'{left_file_name} value = {left_value} / ' \
'{right_file_name} value= {right_value}'
d1 = d.copy()
d1.update(kw)
s = fmt.format(**d1)
# s = s.rstrip()
s = s[0].upper() + s[1:] # sample output doesn't match input
print(s)
def get(self):
item = self._buffer.popitem(last=False)
self.fill_buffer()
return item
def fill_buffer(self):
if self._fp is None:
return
while len(self._buffer) < self._max_diff:
row = self._fp.readline().split(self._delim)
if not row:
self._fp.close()
self._fp = None
return
entry = self._buffer.setdefault(row[0], [])
entry.append(row[1:])
def __contains__(self, key):
self.fill_buffer()
return key in self._buffer
rb1 = RowBuffer(sys.argv[1])
rb2 = RowBuffer(sys.argv[2])
rb1.compare(rb2)
答案2
这是对您的问题的(远非优雅的)部分解决方案。它使用第一列作为 id 列(它不必是第一列,但你绝对必须有一个)并引入第三个维度suffix
来存储同一键的多次出现。最后它尝试找到文件 2 中那些在文件 1 中没有找到的键。
BEGIN {
IGNORECASE = 1
}
NR==1 {
for (i = 1; i <= NF; i++)
header[i] = $i
suffix = 0
previous_key=""
}
NR==FNR {
if ($1 == previous_key) {
suffix = suffix + 1
max_suffix[$1] = suffix
} else
suffix = 0
for (i = 1; i <= NF; i++) {
A[$1,suffix,i] = $i
}
key_count[$1] = key_count[$1] + 1
previous_key = $1
next
}
{
if ($1 == previous_key)
suffix = suffix + 1
else
suffix = 0
previous_key = $1
if (A[$1,suffix,1] != "") {
for (i = 2; i <= NF; i++)
if (A[$1,suffix,i] != $i) {
print header[1]"#-"$1": " header[i] "- " ARGV[1] " value= ", A[$1,suffix,i]" / " ARGV[2] " value= "$i
}
key_count[$1] = key_count[$1] - 1
}
else
for (i = 2; i <= NF; i++)
print header[1]"#-"$1": " header[i] "- " ARGV[1] " value= ", " / " ARGV[2] " value= "$i
}
END {
for (missing_key in key_count)
if (key_count[missing_key] > 0) {
for (suffix = max_suffix[missing_key] - key_count[missing_key] + 1; suffix <= C[missing_key]; suffix++)
for (i = 2; i <= NF; i++)
print header[1]"#-"missing_key": " header[i] "- " ARGV[1] " value= ", A[missing_key,suffix,i] " / " ARGV[2] " value= "
}
}
有一个警告:文件 2 中的不匹配条目始终打印在末尾,并且不根据文件中的位置进行排序。此外,这些行的排序是任意的。我想这可以通过将结果传递到命令中来实现sort
。