用replace实现grep
Greptile的Python项目详细描述
灰色
python中的快速grep实现,具有replace特性
usage: greptile.py [-h] [-v] [-x EXTENSIONS [EXTENSIONS ...]] [-r] [-l] [-i] [-g REPLACE_EXPR] [-f REPLACE_EXPR] expression [file] file search and replace with regular expressions positional arguments: expression regular expression file file path (or directory if -r is used) optional arguments: -h, --help show this help message and exit -v, --version show program's version number and exit -x EXTENSIONS [EXTENSIONS ...], --extensions EXTENSIONS [EXTENSIONS ...] restrict search to file extensions (ex: .py .txt .java .xml) -r, --recursive recursively search in path -l, --list list files matching pattern -i, --inplace update the file inplace (with -g or -f) -g REPLACE_EXPR, --replace-global REPLACE_EXPR global replacement expression -f REPLACE_EXPR, --replace-first REPLACE_EXPR first occurrence replacement expression
为什么这么快?
因为它只使用发电机,爬行动物从不分配大的 列表,它总是一次处理一个文件中的一行。你可以做一个 递归搜索大文件和大目录,如/,而不搜索 内存开销。
示例:
搜索"import"in./greptile.py:
$ ./greptile.py "import" ./greptile.py
import re import os import sys import argparse
从包含Copyright:
的python文件中的~/行递归搜索$ ./greptile.py -x .py -r "Copyright" ~/
/Users/nic/Library/Android/sdk/platform-tools/systrace/systrace-legacy.py 2: # Copyright (c) 2011 The Chromium Authors. All rights reserved. /Users/nic/Library/Android/sdk/platform-tools/systrace/systrace.py 2: # Copyright (c) 2011 The Chromium Authors. All rights reserved. /Users/nic/Library/Android/sdk/platform-tools/systrace/systrace_agent.py 0: # Copyright (c) 2015 The Chromium Authors. All rights reserved. /Users/nic/Library/Android/sdk/platform-tools/systrace/util.py 0: # Copyright (c) 2015 The Chromium Authors. All rights reserved. /Users/nic/Library/Android/sdk/platform-tools/systrace/agents/__init__.py 0: # Copyright (c) 2015 The Chromium Authors. All rights reserved. /Users/nic/Library/Android/sdk/platform-tools/systrace/agents/atrace_agent.py 0: # Copyright (c) 2015 The Chromium Authors. All rights reserved. ...
用python替换和简单分组re.sub语法:
$ greptile.py "\[(.*)\]\((.*)\)" README.md -g "<a href=\"\2\">\1</a>"| diff -u README.md -
--- README.md 2016-04-19 22:37:20.000000000 +0200 +++ - 2016-04-25 14:54:24.000000000 +0200 @@ -1,4 +1,4 @@ -![Agera](https://github.com/google/agera/blob/master/doc/images/agera.png) +!<a href="https://github.com/google/agera/blob/master/doc/images/agera.png">Agera</a> Reactive Programming for Android ================================
原料药:
importgreptile# Replace "import" by "export" from dir `./`, in all files and these extensions: .py, .xml, .javagreptile.replace('import','export','./','.py','.xml','.java')# Return filenames of all files containing the text "import" from dir `./` and .py, .xml, .javamy_list=greptile.grep_rl('import','./','.py','.xml','.java')# same as calling replace()greptile.sed_i(my_list,'import','export')