Grep and Python

后端 未结 7 739
暗喜
暗喜 2020-12-02 09:36

I need a way of searching a file using grep via a regular expression from the Unix command line. For example when I type in the command line:

python pythonfi         


        
相关标签:
7条回答
  • 2020-12-02 10:01

    Adapted from a grep in python.

    Accepts a list of filenames via [2:], does no exception handling:

    #!/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:] works, if you run it as an standalone executable, meaning

    chmod +x

    first

    0 讨论(0)
  • 2020-12-02 10:03

    You might be interested in pyp. Citing my other answer:

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

    0 讨论(0)
  • 2020-12-02 10:06
    1. use sys.argv to get the command-line parameters
    2. use open(), read() to manipulate file
    3. use the Python re module to match lines
    0 讨论(0)
  • 2020-12-02 10:11

    You can use python-textops3 :

    from textops import *
    
    print('\n'.join(cat(f) | grep(search_term)))
    

    with python-textops3 you can use unix-like commands with pipes

    0 讨论(0)
  • 2020-12-02 10:18

    Concise and memory efficient:

    #!/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)))
    

    It works like egrep (without too much error handling), e.g.:

    cat input-file | grep.py "RE"
    

    And here is the one-liner:

    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"
    
    0 讨论(0)
  • 2020-12-02 10:18

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

    0 讨论(0)
提交回复
热议问题