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,
참고할 사항 :
search
match
문자열의 아무 곳이나 찾는 대신- 캐리지 리턴
,
을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"
를 통해 파일 이름 목록을 허용하고 [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
먼저
sys.argv
명령 줄 매개 변수를 가져 오는 데 사용- 사용
open()
,read()
파일을 조작 할 수 - 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
'Program Tip' 카테고리의 다른 글
HashSet (0) | 2020.11.21 |
---|---|
도커 진입 점 스크립트에 대해 set -e 및 exec“$ @”의 기능은 무엇입니까? (0) | 2020.11.21 |
파이썬 : 두 단어로 된 이름을 가진 모듈 이름 지정 (0) | 2020.11.21 |
더 큰 애플리케이션 범위를 제공하기 위해 이전 버전의 libc에 대한 링크 (0) | 2020.11.21 |
동일한 열에서 여러 WHERE 조건으로 선택 (0) | 2020.11.21 |