Ubuntu – Bash cut and grep commands through python

command linegreppython

I've tried to read a txt file and find the lines which contain a certain word "checkout_revision". I want to find these lines one by one in a for loop and store them in my variable, let say temp. I heard grep with cut is suitable for this. However I could not do that. Is there anyone to help me? Here is my code :

for line in intersect:
        cmd=""" grep "CHECKOUT_REVISION" |cut -d\'\"\' -f2"""%fst_directory
        cmd_test=os.system(cmd)

Best Answer

Suppose there is a file /home/eday/test.txt with the contents bellow:

this is a test


another line

CHECKOUT_REVISION this must be stored

some other things
CHECKOUT_REVISION another line to store

The following Python script will read the file stored in my_file variable looking for what is stored in look_for variable and if it finds a match, it will store it in temp variable which is a list variable.

Finally it will print to the output the contents of temp You can comment out or delete the printing line.

#!/usr/bin/env python

# path to the file to read from
my_file = "/home/eday/test.txt"
# what to look in each line
look_for = "CHECKOUT_REVISION"
# variable to store lines containing CHECKOUT_REVISION
temp = []

with open(my_file, "r") as file_to_read:
    for line in file_to_read:
        if look_for in line:
            temp.append(line)

# print the contents of temp variable
print (temp)

the above script will have the following output in terminal:

$ ['CHECKOUT_REVISION this must be stored', 'CHECKOUT_REVISION another line to store']