6

I have a directory like this:

<folder1>
<folder2>
<folder3>
file1
file2
file3

What is the rm command like that removes only file1, file2, file3 but leaves folder1, folder2 and folder3 and their content untouched?

1
  • 1
    is there any pattern or you just want to remove all files in that directory leaving the directories as it is ?
    – heemayl
    Aug 25, 2015 at 9:26

2 Answers 2

10

rm won't delete directories by default. So in your example, assuming you're in the parent directory and those are all the files, all you need is:

rm *

That's a dangerous command. If you forget where you are, a command like that can wipe out important $HOME files, wipe out a load of photos, cancel Christmas, etc, etc, etc. Make sure you know what * is selecting before you run it. echo * is a good way to test the expansion.

A sane person presented with file1 file2 file3 might run rm file* or rm file{1..3} to use some of Bash's expansion code and not catch any stragglers you hadn't thought of in the crossfire.


To delete directories you need to specify either:

  • -d to delete empty directories, or
  • -r to recursively delete files and their directories.
2
  • 1
    If you wanted to be slightly more selective with the files that are removed, bash wildcards let you do that. For example rm file* will delete ever file beginning with "file"
    – AJefferiss
    Aug 25, 2015 at 9:32
  • what if I want to recursively delete all files but not delete any folders it encounters?
    – gota
    Sep 13, 2018 at 11:17
2

As @Oli said in his answer

rm won't delete directories by default.


But you could also use find

find . -maxdepth 1 -type f -exec rm "{}" \;

or with a search pattern

find . -maxdepth 1 -type f -name "a*" -exec rm "{}" \;

Example

% tree
.
├── a
├── b
├── bar
│   ├── a
│   └── b
└── foo
    ├── a
    └── b

%  find . -maxdepth 1 -type f -exec rm "{}" \;

% tree
.
├── bar
│   ├── a
│   └── b
└── foo
    ├── a
    └── b

or with a search pattern

% find . -maxdepth 1 -type f -name "a*" -exec rm "{}" \;

% tree                                                  
.
├── b
├── bar
│   ├── a
│   └── b
└── foo
    ├── a
    └── b

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .