Home > other >  Go inside several directories and execute something, EXCLUDING few directories with certain string i
Go inside several directories and execute something, EXCLUDING few directories with certain string i

Time:07-12

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 (abcthis && abcthat); do (something); done

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

CodePudding user response:

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.

CodePudding user response:

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
  • Related