2

我有这样一个问题:我有两个带有密钥的文件:

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。

4

4 回答 4

4

您可以使用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-09T11:46:48.653 回答
3

的丑陋工作:

sed -r 's#(\w+)[,;]\s*#/\1/{x;s/.*/\&\1,/;x};#g;s#.*#&x;s/,$/;/#' file1|sed -rf - file2 > res1.txt
sed -r 's#(\w+),\s#\1[,;]\\s*|#g;s#(.*);#s/\1//g#' file1|sed -rf - file2 > res2.txt

$猫文件1文件2
aa、bb、cc、dd、ee、ff、gg;
aa、bb、cc、zz、yy、ww、oo;

$ sed -r 's#(\w+)[,;]\s*#/\1/{x;s/.*/\&\1,/;x};#g;s#.*#&x ;s/,$/;/#' 文件1|sed -rf - 文件2
aa,bb,cc;

$ sed -r 's#(\w+),\s#\1[,;]\\s*|#g;s#(.*);#s/\1//g#' file1|sed -rf - 文件2
zz, yy, ww, oo;

报价Windows

sed -r "s#(\w+)[,;]\s*#/\1/{x;s/.*/\&\1,/;x};#g;s#.*#&x;s/,$/;/#" file1|sed -rf - file2 > res1.txt
sed -r "s#(\w+),\s#\1[,;]\\s*|#g;s#(.*);#s/\1//g#" file1|sed -rf - file2 > res2.txt
于 2013-07-09T20:30:47.313 回答
1

在 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-09T13:22:56.953 回答
1

每个 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 file2
于 2013-07-09T12:47:37.790 回答