Search code examples
pythonbashshellsh

Shell find logic into Python script


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 returns 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 this:

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. For example, what is the following command in bash 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`

Solution

  • 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