0

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)
2
  • 1
    fnmatch won't work with your pattern, use un*x style patterns. And os.listdir doesn't recurse, by design. You have to use os.walk Commented Jan 20, 2023 at 19:40
  • 1
    TEST_F( isn't a filename pattern, it's the regular expression you're matching inside the files. grep syntax is grep <options> <pattern> <filenames> Commented Jan 20, 2023 at 20:25

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

10 Comments

Thanks a lot, Barmar for the insight. May I ask you one more question if you don't mind? for example. "cat testcases | grep -v testcase | while read LINE" or "grep -R "@Test" -A 1 | grep void | while read LINE". what will be the best approach to convert bash to python? Thanks a lot
And also how to add sed and cut into this solution? grep -R "TEST_F(" | sed s/"TEST_F("/"#"/g | cut -f2 -d "#" | while read LINE sorry for the dummy question and I am quite new to python
As I explained, split() and [1] are doing what sed and cut do.
grep -v testcase turns into reading the lines of the file, and then doing if 'testcase' not in line: in the loop.
grep XXX -A 1 | grep void translates to reading the file line by line. If the line matches XXX, read the next line, then do if 'void' in nextline:
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.