L
L
lagudal2020-01-27 13:18:33
linux
lagudal, 2020-01-27 13:18:33

How to delete recursively all files and directories, except files of the same type?

I 'm a little confused,
the situation seems simple, but something doesn't work.
In general, there is a directory, its path from the system root, let's say /var/www/site/dir
There are several levels of nesting in the directory. It is necessary to clear everything that is inside this directory, leaving only all files with a specific extension, let's say in the example they will be .txt files.
Those. directories that do not contain txt files should be deleted completely, and in those that contain - everything except txt is deleted.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
R
Rsa97, 2020-01-27
@lagudal

find /каталог ! -name \*.txt -type f -delete && find /каталог -type d -empty -delete

V
Victor Taran, 2020-01-27
@shambler81

find -type f /var/www/site/dir- an array of files, by the way, you did not say whether it is necessary to delete directories in which there are 0 files,
-execexecute the command to
grep -v "*\.txt$" | rm -fv {}exclude everything from the array with text at the end, well, and
actually delete one line further, you yourself will come up.
If you can’t master it, write

V
Valdemar Smorman, 2020-01-27
@smorman

There are few sane ways in MAN, alas...
You can, for example, specify the extensions that need to be removed
rm *.jpg *.gif
without specifying .txt
Better, as the guys above wrote through find

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question