Check if file is in a folder with a certain name before proceeding

Viewed 35

So, I have this simple script which converts videos in a folder into a format which the R4DS can play.

#!/bin/bash
scr='/home/user/dpgv4/dpgv4.py';mkdir -p 'DPG_DS'
find '../Exports' -name "*1080pnornmain.mp4" -exec python3 "$scr" {} \;

The problem is, some of the videos are invalid and won't play, and I've moved those videos to a different directory inside the Exports folder. What I want to do is check to make sure the files are in a folder called new before running the python script on them, preferably within the find command. The path should look something like this:

../Exports/(anything here)/new/*1080pnornmain.mp4

Please note that (anything here) text does not indicate a single directory, it could be something like foo/bar, foo/b/ar, f/o/o/b/a/r, etc.

1 Answers

You cannot use -name because the search is on the path now. My first solution was:

find ./Exports -path '**/new/*1080pnornmain.mp4' -exec python3 "$scr" {} \;

But, as @dan pointed out in the comments, it is wrong because it uses the globstar wildcard (**) unnecessarily:

This checks if /new/ is somewhere in the preceding path, it doesn't have to be a direct parent.

So, the star is not enough here. Another possibility, using find only, could be this one:

find ./Exports -regex '.*/new/[^\/]*1080pnornmain.mp4' -exec python3 "$scr" {} \;

This regex matches:

  1. any number of nested folders before new with .*/new
  2. any character (except / to leave out further subpaths) + your filename with [^\/]*1080pnornmain.mp4

Performances could degrade given that it uses regular expressions.


Generally, instead of using the -exec option of the find command, you should opt to passing each line of find output to xargs because of the more efficient thread spawning, like:

find ./Exports -regex '.*/new/[^\/]*1080pnornmain.mp4' | xargs -0 -I '{}' python3 "$scr" '{}'
Related