LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   Remove sub-directories, yet preserve others (http://www.linuxquestions.org/questions/programming-9/remove-sub-directories-yet-preserve-others-4175440954/)

dwhitney67 12-11-2012 06:34 AM

Remove sub-directories, yet preserve others
 
Hi,

I'm trying to write a bash script in which I want it to remove all sub-directories except two ('core' and 'java') within a particular directory.

Here's what I got:
Code:

for dir in ${DIRS[@]}; do
    pushd ${dir} >& /dev/null
    find . -maxdepth 1 -type d \( -name . -o -name core -o -name java \) -prune -o -print0 | xargs rm -rf
    popd >& /dev/null
done

I know that the problem is with the "-name ." in the exclusion list of the find-statement above.

If I remove the "-name . -o" from the find-statement above, then I get errors such as:
Code:

xargs: WARNING: a NUL character occurred in the input.  It cannot be passed through in the argument list.  Did you mean to use the --null option?
rm: cannot remove directory: `.'

With the original statement, as I have shown above, none of the unwanted sub-directories are being removed. Can someone please help me sort this issue out?

millgates 12-11-2012 06:44 AM

Hi, how about
Code:

for dir in "${DIRS[@]}"; do
    find "$dir" -maxdepth 1 -mindepth 1 ! -name java ! -name core | xargs rm -rf
done

also, don't forget to quote the variables.

colucix 12-11-2012 06:55 AM

Well, if you put . among the directories to exclude, nothing is printed out by the find command. Actually the rm command doesn't work on . and .. since they are a sort of aliases and not the real name of a directory. Anyway, if you want to be sure use -mindepth to exclude the current working directory:
Code:

find . -mindepth 1 -maxdepth 1 -type d
Moreover, in your command line you missed the -0 option of xargs to be used in conjuction with -print0, hence the "a NUL character occurred in the input" warning message. Looking at the complete message from your second command, it shows that it cannot remove directory . but it should have removed the other ones. Anyway, here is a correct command line:
Code:

find . -mindepth 1 -maxdepth 1 -type d \( -wholename ./core -o -wholename ./java \) -prune -o -print0 | xargs -0 rm -rf
or shortly
Code:

find . -mindepth 1 -maxdepth 1 -type d \( -wholename ./core -o -wholename ./java \) -prune -o -exec rm -rf {} \;
Hope this helps.

dwhitney67 12-11-2012 06:58 AM

Quote:

Originally Posted by millgates (Post 4846925)
Hi, how about
Code:

for dir in "${DIRS[@]}"; do
    find "$dir" -maxdepth 1 -mindepth 1 ! -name java ! -name core | xargs rm -rf
done

also, don't forget to quote the variables.

That works... thanks!!!


All times are GMT -5. The time now is 07:47 AM.