Sunday, February 27, 2022

[SOLVED] Adding test_ in front of a file name with path

Issue

I have a list of files stored in a text file, and if a Python file is found in that list. I want to the corresponding test file using Pytest.

My file looks like this:

/folder1/file1.txt
/folder1/file2.jpg
/folder1/file3.md
/folder1/file4.py
/folder1/folder2/file5.py

When 4th/5th files are found, I want to run the command pytest like:

pytest /folder1/test_file4.py
pytest /folder1/folder2/test_file5.py

Currently, I am using this command:

cat /workspace/filelist.txt | while read line; do if [[ $$line == *.py ]]; then exec "pytest test_$${line}"; fi; done;

which is not working correctly, as I have file path in the text as well. Any idea how to implement this?


Solution

Using Bash's variable substring removal to add the test_. One-liner:

$ while read line; do if [[ $line == *.py ]]; then echo "pytest ${line%/*}/test_${line##*/}"; fi; done < file

In more readable form:

while read line
do 
  if [[ $line == *.py ]]
  then 
    echo "pytest ${line%/*}/test_${line##*/}"
  fi
done < file

Output:

pytest /folder1/test_file4.py
pytest /folder1/folder2/test_file5.py

Don't know anything about the Google Cloudbuild so I'll let you experiment with the double dollar signs.

Update:

In case there are files already with test_ prefix, use this bash script that utilizes extglob in variable substring removal:

shopt -s extglob                                           # notice
while read line
do
    if [[ $line == *.py ]]
    then
        echo "pytest ${line%/*}/test_${line##*/?(test_)}"  # notice
    fi
done < file


Answered By - James Brown
Answer Checked By - David Marino (WPSolving Volunteer)