我有这样一个问题:我有两个带有密钥的文件:
file1: aa, bb, cc, dd, ee, ff, gg;
file2: aa, bb, cc, zz, yy, ww, oo;我需要使用grep/sed编写一个脚本来生成两个文件:
res1.txt - will contain similar keys from both files: aa, bb, cc;
res2.txt - will contain ONLY keys from file2 which differs from files1: zz, yy, ww, oo.我可以用这个工具来完成它吗?我如何或者需要使用python脚本来完成这个工作呢?谢谢。
我在使用Windows。
发布于 2013-07-09 13:22:56
在Python中,您可以执行以下操作。
string1 = "aa, bb, cc, dd, ee, ff, gg;"
string2 = "aa, bb, cc, zz, yy, ww, oo;"
list1 = string1.rstrip(';').split(', ')
list2 = string2.rstrip(';').split(', ')
common_words = filter(lambda x: x in list1, list2)
unique_words = filter(lambda x: x not in list1, list2)
>>> common_words
['aa', 'bb', 'cc']
>>> unique_words
['zz', 'yy', 'ww', 'oo']然后,如果需要,可以将这些内容写入文件。
例如:
common_string = ', '.join(common_words) + ';'
with open("common.txt", 'w') as common_file:
common_file.write(common_string)发布于 2013-07-09 11:46:48
您可以使用comm显示公共行,但必须对文件进行排序(并通过tr将它们转换为每行格式的键):
comm -12 <(tr -s ' ,' '\n' < file1 | sort) <(tr -s ' ,' '\n' < file2 | sort)
comm -13 <(tr -s ' ,' '\n' < file1 | sort) <(tr -s ' ,' '\n' < file2 | sort)发布于 2013-07-09 12:47:37
每个UNIX安装附带的通用文本处理工具名为awk。
awk -F', *|;' '
NR==FNR { for (i=1; i<NF;i++) file1[$i]; next }
{
for (i=1; i<NF; i++) {
sfx = ($i in file1 ? 1 : 2)
printf "%s%s", sep[sfx], $i > ("res" sfx ".txt")
sep[sfx]=", "
}
}
END { for (sfx in sep) print ";" > ("res" sfx ".txt") }
' file1 file2https://stackoverflow.com/questions/17547218
复制相似问题