D
D
danilok47742016-10-02 16:45:32
linux
danilok4774, 2016-10-02 16:45:32

How to search for a keyword in a file of all lines where it is present?

I have a file with several lines in it.
I need to search for a keyword or phrase in a file to find all lines containing that word or that phrase.
I know that this is done through the re library
. There is re.findall(r'pattern', 'text to search')
You need to do this through the variable name. Well, for example, this is a variable var1 and var2. I need to replace quoted texts with variable names, but how?
And you also need to replace the 'text to search' with the name of the variable containing the path to the file in which you want to search. The file is text. You need to search throughout the file.
Hope you can help
Thanks in advance

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander, 2016-10-02
@fireSparrow

Regular expressions are a very powerful tool, and your task is quite simple.
For your case, instead of re.findall, it is better to use a test for the occurrence of a substring using the in keyword.

with open(filename,"r") as myfile:
    for line in myfile:
        if var1 in line:
            print(line)

Here, instead of filename, insert the path and name to your file, and instead of var1 - what to look for.
Well, instead of print(line) you can do whatever you need with the found line line - for example, save it somewhere.

A
Alexander, 2016-10-02
@keich

It's hard to understand. Do you need python?

import re
filename="file.txt"
pattern="\S*y{2,5}\S* "
prog = re.compile(pattern)
with open(filename,"r") as myfile:
    for line in myfile:
        if prog.match(line):
            print(line)

Or maybe you just need grep?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question