简体   繁体   中英

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.

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, ie 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".

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,/*[^/]\+/*$,,'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM