Simplified grep in python

Viewed 32

I need to create a simplified version of grep in python which will print a line when a keyword is used such as using this command "python mygrep.py duck animals.txt" and getting the output, "The duck goes quack". I have a file where it contains different outputs but I'm not sure how to get it to print the line that contains the "keyword" such as the line with "duck" in it. Im suppose to only use "import sys" and not "re" since its suppose to be a simple version.

import sys

def main():
    if len(sys.argv) != 3:
        exit('Please pass 2 arguments.')

    search_text = sys.argv[1]
    filename = sys.argv[2]

    with open("animals.txt", 'r') as f:
       text = f.read()
    for line in text:
        print(line)


if __name__ == '__main__':
    main()
2 Answers

The operator 'in' should be sufficient.

for line in text:
    if search_text in line:
        print(line)

Here is a an implementation of grep in python with after/before feature:

    def _fetch_logs(self, data, log_file, max_result_size, current_result_size):
        after = data.get("after", 0)
        before = data.get("before", 0)
        exceeded_max = False
        result = []
        before_counter = 0
        frame = []
        found = False
        for line in log_file:
            frame.append(line)
            match_patterns = all(self._search_in(data, pattern, line) for pattern in data["patterns"])
            if match_patterns:
                before_counter = len(frame)
                found = True

            if not found and len(frame) > before:
                frame.pop(0)

            if found and len(frame) >= before_counter + after:
                found = False
                before_counter = 0
                result += frame
                frame = []

            if current_result_size + len(result) >= max_result_size:
                exceeded_max = True
                break
        if found:
            result += frame
        return exceeded_max, result
Related