Home > Back-end >  sed shell command into Python script
sed shell command into Python script

Time:01-25

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

shell command is this :

cd ../../../tests/src/main/java
ls
grep -R "@Test" -A 1 | grep void | while read LINE
do
    CLASS=`echo $LINE | cut -f1 -d"." | sed s/"\/"/"\."/g`
    TEST_CASE=`echo $LINE | sed s/"void "/

The logic is inside a directory, reads the filename one by one, includes all sub-folders, then lists the file matches.

grep -R "@Test" -A 1 | grep void translates to reading the file line by line. If the line matches @Test, read the next line, then do if 'void' in nextline

I tried something like follows, but I don't know the sed command exactly doing and how to convert it into python script. for example

CLASS=`echo $LINE | cut -f1 -d"." | sed s/"\/"/"\."/g`
TEST_CASE=`echo $LINE | sed s/"void "/

For retrieve the data send to parameter CLASS and TEST_CASE , I did the cut but I don't know how to do the sed

for root, dirs, files in os.walk(../../../tests/src/main/java):
    for file in files:
        with open(os.path.join(root, file), encoding="utf8", errors='ignore') as f:
            for line in f:
                nextLine = next(f)
                if "@Test" in line:
                    if "void" in nextLine:
                        CLASS = nextLine.split(",")[0]    // How to apply the sed here?
                        TEST_CASE = nextLine // How to apply the sed here?

Any help will be much appreciated

CodePudding user response:

Here is a possible way to convert the shell command into a Python script:

import os

path = "../../../tests/src/main/java"
for root, dirs, files in os.walk(path):
    for file in files:
        with open(os.path.join(root, file), encoding="utf8", errors='ignore') as f:
            lines = f.readlines()
            for i, line in enumerate(lines):
                if "@Test" in line:
                    if "void" in lines[i 1]:
                        # Use .replace() method to replace "/" with "."
                        CLASS = lines[i 1].split(",")[0].replace("/", ".")
                        # Use .replace() method to remove the word "void"
                        TEST_CASE = lines[i 1].replace("void ", "")

-- This script first walks through all the directories, sub-directories, and files in the path "../../../tests/src/main/java". Then, it reads the content of each file, and for each line, it checks if the line contains "@Test".

If it does, it reads the next line, and checks if it contains "void". If it does, it uses the .split() method to retrieve the first element of the line, which is separated by a ",", and then replaces the "/" with "." to get the value of CLASS. Then it uses the .replace() method to remove the word "void" from the nextLine to get the value of TEST_CASE.

  • Related