Home > Blockchain >  grep bash command into Python script
grep bash command into Python script

Time:01-21

There is a bash command, I am trying to convert the logic into python. But I don't know what to do, I need some help with that.

bash command is this :

ls
ls *
TODAY=`date  %Y-%m-%d`
cd xx/xx/autotests/
grep -R "TEST_F(" | sed s/"TEST_F("/"#"/g | cut -f2 -d "#" | while read LINE

The logic is inside a directory, reads the filename one by one, includes all sub-folders, then lists the file matches. Any help here will be much appreciated

I tried something like follows, but it is not what I would like to have. And there are some subfolders inside, which the code is not reading the file inside them

import fnmatch
import os
from datetime import datetime

time = datetime.now()

dir_path = "/xx/xx/autotests"
dirs = os.listdir(dir_path)
TODAY = time.strftime("%Y-%m-%d")

filesOfDirectory = os.listdir(dir_path)
print(filesOfDirectory)
pattern = "TEST_F("
for file in filesOfDirectory:
    if fnmatch.fnmatch(file, pattern):
        print(file)

CodePudding user response:

Use os.walk() to scan the directory recursively.

Open each file, loop through the lines of the file looking for lines with "TEST_F(". Then extract the part of the line after that (that's what sed and cut are doing).

for root, dirs, files in os.walk(dir_path):
    for file in files:
        with open(os.path.join(root, file)) as f:
            for line in f:
                if "TEST_F(" in line:
                    data = line.split("TEST_F(")[1]
                    print(data)
  • Related