Only delete files but not folders with rm
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?
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.
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