Grep and Python

后端 未结 7 768
暗喜
暗喜 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: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"
    

提交回复
热议问题