2013-07-09 7 views
2

이러한 문제를 두 그렙에 선이나 나오지도 병합 : 나는 키 두 개의 파일이 있습니다내가 가진

:

file1: aa, bb, cc, dd, ee, ff, gg; 

file2: aa, bb, cc, zz, yy, ww, oo; 

을 내가 GREP을 사용하여 스크립트를 작성해야/두 개의 파일을 생성을 나오지

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. 

이 도구로 어떻게 할 수 있습니까?이 작업을 수행하기 위해 파이썬 스크립트를 사용해야합니까? 감사.

Windows를 사용하고 있습니다.

답변

1

파이썬에서 다음을 수행 할 수 있습니다. 당신이 원하는 경우

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'] 

그런 다음 파일에 다음을 작성할 수 있습니다.

예컨대 : GNU 에 대한

common_string = ', '.join(common_words) + ';' 
with open("common.txt", 'w') as common_file: 
    common_file.write(common_string) 
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) 
+0

무엇이 통신인가요? 나는 창문 PC에있다. – yozhik

+3

@yozhik - 그것은 당신의 질문에 당신의 창문에 언급하는 것이 유용 할 것이다. 원하는 솔루션으로 전통적으로 유닉스 툴 2 개를 명명하면 유닉스 상에 있다고 가정하는 것이 합리적입니다. –

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 
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 

 
$ cat file1 file2 
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/,$/;/#' file1|sed -rf - file2 
aa,bb,cc; 

$ sed -r 's#(\w+),\s#\1[,;]\\s*|#g;s#(.*);#s/\1//g#' file1|sed -rf - file2 
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