Program Tip

Grep 및 Python

programtip 2020. 11. 21. 09:24
반응형

Grep 및 Python


Unix 명령 줄에서 정규식을 통해 grep을 사용하여 파일을 검색하는 방법이 필요합니다. 예를 들어 명령 줄에 입력 할 때 :

python pythonfile.py 'RE' 'file-to-be-searched'

'RE'파일에서 검색하고 일치하는 줄을 인쇄 하려면 정규식이 필요합니다 .

내가 가진 코드는 다음과 같습니다.

import re
import sys

search_term = sys.argv[1]
f = sys.argv[2]

for line in open(f, 'r'):
    if re.search(search_term, line):
        print line,
        if line == None:
            print 'no matches found'

하지만 존재 no matches found하지 않는 단어를 입력하면 인쇄되지 않습니다.


당연한 질문은 왜 grep을 사용하지 않는 것입니까?! 하지만 당신이 할 수 없다고 가정하면 ...

import re
import sys

file = open(sys.argv[2], "r")

for line in file:
     if re.search(sys.argv[1], line):
         print line,

참고할 사항 :

  • searchmatch문자열의 아무 곳이나 찾는 대신
  • 캐리지 리턴 ,print제거한 쉼표 ( ) (줄에 하나가 있음)
  • argv 파이썬 파일 이름을 포함하므로 변수는 1부터 시작해야합니다.

이것은 여러 인수를 처리하거나 (grep처럼) 와일드 카드를 확장하지 않습니다 (유닉스 쉘처럼). 이 기능을 원하면 다음을 사용하여 얻을 수 있습니다.

import re
import sys
import glob

for arg in sys.argv[2:]:
    for file in glob.iglob(arg):
        for line in open(file, 'r'):
            if re.search(sys.argv[1], line):
                print line,

간결하고 효율적인 메모리 :

#!/usr/bin/env python
# file: grep.py
import re, sys

map(sys.stdout.write,(l for l in sys.stdin if re.search(sys.argv[1],l)))

egrep (너무 많은 오류 처리없이)처럼 작동합니다. 예 :

cat input-file | grep.py "RE"

그리고 여기에 한 줄짜리가 있습니다.

cat input-file | python -c "import re,sys;map(sys.stdout.write,(l for l in sys.stdin if re.search(sys.argv[1],l)))" "RE"

pythongrep에서 수정되었습니다 .

를 통해 파일 이름 목록을 허용하고 [2:]예외 처리를하지 않습니다.

#!/usr/bin/env python
import re, sys, os

for f in filter(os.path.isfile, sys.argv[2:]):
    for line in open(f).readlines():
        if re.match(sys.argv[1], line):
            print line

sys.argv[1]resp sys.argv[2:]는 독립 실행 형 실행 파일로 실행하면 작동합니다.

chmod +x

먼저


  1. sys.argv명령 줄 매개 변수를 가져 오는 데 사용
  2. 사용 open(), read()파일을 조작 할 수
  3. Python re 모듈사용하여 줄을 일치 시킵니다.

pyp에 관심이있을 수 있습니다 . 내 다른 대답을 인용하면 :

"The Pyed Piper", or pyp, is a linux command line text manipulation tool similar to awk or sed, but which uses standard python string and list methods as well as custom functions evolved to generate fast results in an intense production environment.


The real problem is that the variable line always has a value. The test for "no matches found" is whether there is a match so the code "if line == None:" should be replaced with "else:"

참고URL : https://stackoverflow.com/questions/1921894/grep-and-python

반응형