1

I have a directory which includes some files and some folders containing other files. I'm trying to remove these files in the main directory without touching the folders or their contents.

I'm using this

rm /media/d/data/* 

it it working fine and only delete the files, but I wonder why the terminal displays this message:

rm: cannot remove /media/d/data/dd1: Is a directory

and same message appears for all the folders found under the main folder. Can anyone explain? and is there is a way not to display this message on terminal?

4 Answers 4

3

By default, rm does not delete directories. If you want the directories to be removed, use rm -rf. If you want to suppress the message, use rm <dir> 2>/dev/null. Note that all other error message get suppressed, too.

1
  • I think rm -r would do..no need to use -f.. Commented Mar 14, 2015 at 15:00
2

This * picks up both files and directories. To delete files only try this

find /media/d/data/ -maxdepth 1 -type f -delete 
2
  • Can't I use rm to do this? Commented Mar 13, 2015 at 8:21
  • You have a few options: find /media/d/data/ -maxdepth 1 -type f -print0 | xargs -0 -i rm {} Or you can just use rm and get rid of the error messages: rm /media/d/data/* 2>/dev/null Commented Mar 13, 2015 at 8:23
2

POSIXly:

find ! -name . -prune -type f -exec rm -f {} + 
2
  • so where do I put my directory /media/d/data/ in this command? Commented Mar 13, 2015 at 11:54
  • @shepherd: You need to cd to /media/d/data Commented Mar 13, 2015 at 11:55
1

rm deletes the files you tell it to. * expands to all files (including directories), so you're telling rm to delete directories, which it won't do.

Most shells have no way to exclude directories from a wildcard pattern. Wildcard patterns only match files by name, not by type. You can use find instead.

Zsh has glob qualifiers which can match files by type, date, etc. In zsh, you can use

rm *(.) 

to delete all regular files, or variants like rm *(-.) to delete regular files and symbolic link to regular files, rm *(^/) to delete all files except directories, etc.

Note also that * omits dot files (files whose name begins with .). find will include them. In zsh, * omits dot files by default; you can add D inside the parentheses (e.g. rm *(.D)) to include them.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.