简体   繁体   中英

Go inside several directories and execute something, EXCLUDING few directories with certain string in the directory name

I have 100s of directories with either “this”, “that” or “nope” in their names. Example:

./abc_3737_this_123 ./abc_9879_this_456 ./abc_2696_that_478 ./abc_8628_nope_958 ./abc_9152_nope_058

I want to get inside all of these dir/subdir EXCLUDING the dir containing “nope” in their names. I simply want the code to leave directories with “nope” in them alone; no getting inside, no checking subdir.

Currently I am using this for all dir:

for dir in abc* ; do (something); done

I want something like:

for dir in (abc this && abc that ); do (something); done

I am sorry of this very silly, I am very new to scripting. Thank you for your time.

Well, you have a number of options. What's your shell? If you're using bash, you can shopt -s extglob and then do either:

for dir in abc_*_@(this|that)_*; do

to be inclusive, or

for dir in abc_*_!(nope)_*; do

to be exclusive.

If you're using zsh, you can setopt kshglob to make the above work, or use setopt extendedglob and these instead:

for dir in abc_*_(this|that)_*; do


for dir in abc_*_^nope_*; do

You could also use find , but you'd have to either use it to build a list to loop over, or else turn your loop body into a single command that you ccould pass to to find or xargs to execute.

find . -maxdepth 1 \( \( -not -name \*nope\* \) -or -prune \) -print0 | xargs -r -0 do_something
while IFS= read -r dir; do 
    echo "$dir"
done < <(find ./*this* ./*that* -maxdepth 0 -type d)
# or < <(find . -maxdepth 1 -type d |grep -E '.*this.*|.*this.*')

# Example
$ while IFS= read -r dir; do echo " -  $dir"; done < <(find /*m*e* /*oo* -maxdepth 0 -type d)
-  /home
-  /media
-  /boot
-  /root

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