0

For this type of dir structure :

\\rdwlhsdevserver\root\user1\folders\testdat.txt
\\rdwlhsdevserver\root\abhay\testdat.txt
\\rdwlhsdevserver\root\testuser\folders1\folder2\testdat.txt
\\rdwlhsdevserver\root\devadmin\input\testdat.txt
\\rdwlhsdevserver\root\admin\testdata\testdat.txt

I know that I can use rm -rf <<folderPath>> to delete parent folder and all sub-folders, but I want to delete all folders and files except \\\rdwlhsdevserver\root\Childfolder

After running cmd, output should be like:

\\rdwlhsdevserver\root\user1\
\\rdwlhsdevserver\root\abhay\
\\rdwlhsdevserver\root\testuser\
\\rdwlhsdevserver\root\devadmin\
\\rdwlhsdevserver\root\admin\
2
rm -rf /path/to/root/*/*

NOTE: Please test this first by making a similar test directory structure. Your shell may not support this kind of syntax (I tested on bash and zsh).

2
  • 1
    In bash, that ** is the same as * unless you turn on the globstar option to enable zsh-style recursive globbing. But anyway, here, you'd want */*, not **/*. You'd also need to tell the shell to remove hidden files (add (D) in zsh or turn on the dotglob option in bash). – Stéphane Chazelas Aug 31 '16 at 7:37
  • 1
    Good points. And with globstar on, bash will actually delete the children of root with **/*. zsh will do the same. I am going to update the answer. – Paul Nordin Aug 31 '16 at 7:57
0

With GNU or BSD find:

find /path/to/root -mindepth 2 -delete

With zsh:

rm -rf /path/to/root/*/*(D)

However note that if there are symlinks to directories in /path/to/root, they will be followed to remove the files in them. You may also run into a Arg list too big error which you could work around by enabling the rm builtin:

zmodload zsh/files
rm -rf /path/to/root/*/.(D)

(the builtin version of rm can remove .)

If you don't want to follow symlinks:

zmodload zsh/files
dirs=(/path/to/root/*(D/)) && rm -rf $^dirs/.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.