3

I recently needed to delete all the files within ~40 directories that were within a parent directory, without deleting the directories themselves. I ended up manually doing so, but is there a more efficient way of doing this? I.e., is there a linux command that can do this?

For a more clear picture of what I mean:

HomeDirectoryName --> subdirectoryName --> 4 simulation info files

I had the above path, except there are 40 subdirectories, each of which have he 4 simulation files. I needed to delete all the simulation info files without deleting the "subdirectoryName" directories.

It may not be possible, as I searched everywhere for about an hour before finally deciding to do it manually.

2

3 Answers 3

5

It's very simple with the find command - just use -type f to find only files and not directories

find /path/to/parent/directory -type f -delete

By default, find recurses into subdirectories, so will find all files in the tree from this point down.

2
  • Would that search within the directories in the parent directory as well, or just remove the files in the parent directory?
    – Red Icing
    Oct 26, 2016 at 23:05
  • 1
    that includes parent directory ,too Oct 27, 2016 at 0:32
3

from parent directory run

find -type f -exec rm {} \;

for removing each file individually, or alternatively

find -type f -exec rm {} +

to enqueue multiple files to rm at a time.

For python enthusiasts, here's another solution:

 python -c 'import os;[os.unlink(os.path.join(r,f)) for r,d,fs in os.walk(".") for f in fs]'
4
  • If not using -delete, you should at least use -exec rm -- {} +, so that find doesn't start a new rm for each file.
    – muru
    Oct 27, 2016 at 1:38
  • @muru that can be done for speed if there's a lot of files in the range of thousands, but in the range of couple hundred files, it won't make much difference. Oct 27, 2016 at 1:55
  • You seem to be particularly fond of slow commands.
    – muru
    Oct 27, 2016 at 1:56
  • @muru well, I'm not Russian, that's why I'm not rushing ;) Oct 27, 2016 at 1:56
1

From the parent directory

rm */*

will remove the 160 simulation info files without removing the 40 directories that contain the files.

(It doesn't matter in this case, but it may be useful in the future to know that rm will never remove a directory unless you explicitly ask it to with with -r flag.)

0

You must log in to answer this question.

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