Home > Back-end >  Shell find logic into python script
Shell find logic into python script

Time:01-25

cd db/test/vs
ls
find . -name '*.vrlp' | while read FILENAME
do
    TEST_CASE=`echo $FILENAME | sed s/"\.\/"//g | sed s/"\.vrlp"//g | rev | cut -f1 -d"/" | rev`
    CLASS=`echo $FILENAME | sed s/"\.\/"//g | sed s/"\/$TEST_CASE"//g | sed s/"\.vrlp"//g`
done

There are a lot of class files (FILENAME) as vrlp inside the vs folder, for example :

Currently, if I am running the bash command, it returned all files with .vrlp for me.

a.vrlp
a.ce.template.a.vrlp
abcd.vrlp
abcd.ce.template.a.vrlp
dfe.vrlp
dfe.ce.template.a.vrlp
gdfd.vrlp
gdfd.ce.template.a.vrlp
test001.vrlp
test001.ce.template.a.vrlp
hies.ce.template.a.vrlp
hies.vrlp
....

But what I want is something like as follows:

a.vrlp
abcd.vrlp
dfe.vrlp
gdfd.vrlp
test001.vrlp
hies.vrlp

without any .ce.template.a or any other patterns. How can I filter this in python?

And also I don't know how to convert sed shell command logic into python, any help on there as well? For example the following bash, what the command is doing?

    TEST_CASE=`echo $FILENAME | sed s/"\.\/"//g | sed s/"\.vrlp"//g | rev | cut -f1 -d"/" | rev`
    CLASS=`echo $FILENAME | sed s/"\.\/"//g | sed s/"\/$TEST_CASE"//g | sed s/"\.vrlp"//g`

CodePudding user response:

This might work:

import os

for _, _, files in os.walk('./'):
    for file in files:
        basename = os.path.basename(file)
        # print the file name if it does not contain a dot - adjust to your needs.
        if not '.' in os.path.splitext(basename)[0]:
            print(basename)

If run on a directory with files

foo.vrlp
foo.ce.template.a.vrlp

It will print only

foo.vrlp
  • Related