I am surprised no one mentioned using %d
.
You can list all nested subfolders, and sort them by depth, using:
find . -type d -printf '%d:%p\n' | sort -t: -k1 -g -r > /tmp/foo.txt
where
.
can be replaced with the root folder;
-type d
finds nested subfolders (replace with -type f
for files instead);
%d:%p
prints the depth, followed by the path;
-t:
means the separator is :
;
-k1
means we want to sort by the first key/column;
-g
means that we want to sort numbers;
-r
means that we want the deepest folders to show first.
The result of this command are streamed into file /tmp/foo.txt
(replace as desired, you can also use mktemp
if needed).
The deepest level can then be determined automatically with:
D=$(head -n 1 /tmp/foo.txt | awk -F ":" '{print $1}')
If you want to filter only those folders or files at depth D
, you can use:
awk -F ":" '{ if ($1 == D) print $2 }' /tmp/foo.txt
Finally, to select a line randomly amongst the results, pipe with | shuf -n 1
.
Putting this into a script random_deep_file <Folder> <Depth>
:
Folder=$1
# Sort files by depth into temporary file
Temp=$(mktemp)
find "$Folder" -type f -printf '%d:%p\n' | sort -t: -k1 -g -r >| "$Temp"
# Determine deepest level if not specified
[ $# -lt 2 ] && { D=$(head -n 1 "$Temp" | awk -F ":" '{print $1}'); } || D=$2
# Select a random file at that depth
awk -F ":" "{ if (\$1 == $D) print \$2 }" "$Temp" | shuf -n 1
Note:
If you are on OSX, you need to install (with Homebrew) and use gfind
and gshuf
instead.