deleting only directory not files

Hi Guys,

I want to know wheather it is possible to delete directory not files,

Example:

In one directory there are 10 dirs and 100 files but my req is to delete only dirs not file

Wheather it is possible ?

for d in dir/*/.; do
  rmdir "${d%/.}"
done

This may require minor modifications. ${var%suf} means remove "suf" from the value of $var -- try it with echo instead of rmdir to see what it does, and whether it's suitable for you.

One way of doing it:

ls -l | awk -F'[0-9][0-9]:[0-9][0-9]' '/^d/{print $NF}'| xargs -i rm -rf '{}' \;

However, it doesn't work if there are directory names with spaces in them.

ls -p|awk '/\/$/&&!/\./' | xargs -i rm -rf "{}"

Hi,

Did you test it ... :slight_smile: ? ?

  • Tested on Fedora 8.

What's wrong with:

rm -r */
1 Like

That's right, sometimes we miss the simple...:slight_smile:

yes sometimes we just miss the simplest things. however take note it still suffers from "argument too long" issues if there are too many directories ( maybe there's a workaround somewhere)

# ls -p | grep "/" | wc -l
31998
# rm -r */
bash: /bin/rm: Argument list too long
# ls -p|awk '/\/$/&&!/\./' | xargs -i rm -rf "{}"
# ls -p | grep "/" | wc -l
0

My post was based on the OP requirement (~10dirs).

Anyway, I don't think ls and awk are needed in this case
and I'd try to handle pathological dirnames (embedded spaces, newlines or other special characters) .

yes, that's why rm -f */ is the simplest solution to his problem. No doubt about that.

Just to make it clear,
I don't think ls and awk are needed in the case you describe (argument list too long).

for d in */;do rm -r "$d";done

Or better (needs to be adjusted for xargs that doesn't support the null option):

xargs -0n1000 rm -r < <(printf "%s\000" */)

If you have zsh:

autoload -U zargs
zargs *(/) -- rm -r

damn,
i was just experimenting rm -rf /
i just typed /

find /path -type d -exec rm -rf {} \;