如何通过取消选择特定模式在Unix文件中查找唯一行

时间:2013-06-11 06:45:17

标签: unix

我在Unix中有一个文件,如下所示

">hello"
"hello"
"newuser"
"<newuser"
"newone"

现在我想在文件中找到唯一的匹配项(仅在搜索时排除<>),输出为:

">hello"
"<newuser"
"newone"

3 个答案:

答案 0 :(得分:3)

#!/usr/bin/env python

import sys
seen = set()
for line in sys.stdin:
    word = line.strip().replace('>', '').replace('<', '')
    if word not in seen:
        seen.add(word)
        sys.stdout.write(line)

$ ./uniq.py < file1
">hello"
"newuser"
"newone"

答案 1 :(得分:2)

$ awk '{ w = $1; sub(/[<>]/, "", w) } word[w] == 0 { word[w]++; print $1 }' file1
">hello"
"newuser"
"newone"

答案 2 :(得分:0)

这是Ruby中的关联数组思想。

2.0.0p195 :005 > entries= [">hello", "hello", "newuser", "<newuser", "newone"]
 => [">hello", "hello", "newuser", "<newuser", "newone"] 
2.0.0p195 :006 > entries.reduce({}) { |hash, entry| hash[entry.sub(/[<>]/,'')]=entry; hash}.values
 => ["hello", "<newuser", "newone"]