Grep and Python

后端 未结 7 740
暗喜
暗喜 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:28

    The natural question is why not just use grep?! But assuming you can't...

    import re
    import sys
    
    file = open(sys.argv[2], "r")
    
    for line in file:
         if re.search(sys.argv[1], line):
             print line,
    

    Things to note:

    • search instead of match to find anywhere in string
    • comma (,) after print removes carriage return (line will have one)
    • argv includes python file name, so variables need to start at 1

    This doesn't handle multiple arguments (like grep does) or expand wildcards (like the Unix shell would). If you wanted this functionality you could get it using the following:

    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,
    
    0 讨论(0)
提交回复
热议问题