DeltaIV
DeltaIV

Reputation: 5646

List down all sub-Directories in Bash based on some criteria

I'm writing a script which navigates all subdirs named something like 12, 98, etc., and checks that each one contains a runs subdir. The check is needed for subsequent operations in the script. How can I do that? I managed to write this:

# check that I am in a multi-grid directory, with "runs" subdirectories
for grid in ??; do
    cd $grid
    cd ..       
done

However, ?? also matches stuff like LS, which is not correct. Any ideas on how to fix it?

Next step: in each directory named dd (digit/digit), I need to check that there is a subdirectory named runs, or exit with error. Any idea on how to do that? I thought of using find -type d -name "runs", but it looks recursively inside subdirs, which is wrong, and anyway if find doesn't find a match, I have no idea on how to catch that inside the script.

Upvotes: 0

Views: 77

Answers (2)

choroba
choroba

Reputation: 241868

Loop over the directories, report the missing subdir:

for dir in [0-9][0-9]/ ; do
    [[ -d $dir/runs ]] || { echo $dir ; exit 1 ; }
done

You can use character classes in glob patterns. The / (not \) after the pattern makes it match only directories, i.e. a file named 42 will be skipped.

The next line reads "$dir/runs is a directory, or report it". [[ ... ]] introduces a condition, see man bash for details. -d tests whether a directory exists. || is "or", you can rephrase the line as

if [[ ! -d $dir/runs ]] ; then
    echo $dir
    exit 1
fi

where ! stands for "not".

Upvotes: 1

Akhil Thayyil
Akhil Thayyil

Reputation: 9403

First find all directories with name runs using :

find . -type d -name runs

Note: to restrict to one level you can use find along with -maxdepth

From this extract the previous directory by removing the last word after /

try :

sed 's,/*[^/]\+/*$,,'

Upvotes: 0

Related Questions