Linux удалить все файлы содержащие

Remove all files except some from a directory

There are 2 ways to read this question, and the existing answers cover both interpretations: EITHER: (a) preserve files with the specified names directly located in the target directory and — as rm -r implies — delete everything else, including subdirectories — even if they contain files with the specified names; OR: (b) traverse the entire subtree of the target directory and, in each directory, delete all files except those with the names listed.

To everyone doing this, please make a backup first. I’ve just wasted several days worth of work because I forgot to exclude .git , and not having pushed, I was unable to recover over 30 commits. Make sure you exclude everything you care about, hidden folders included. And set -maxdepth 1 if you’re dealing with directories.

20 Answers 20

find [path] -type f -not -name 'textfile.txt' -not -name 'backup.tar.gz' -delete 

If you don’t specify -type f find will also list directories, which you may not want.

Or a more general solution using the very useful combination find | xargs :

find [path] -type f -not -name 'EXPR' -print0 | xargs -0 rm -- 

for example, delete all non txt-files in the current directory:

find . -type f -not -name '*txt' -print0 | xargs -0 rm -- 

The print0 and -0 combination is needed if there are spaces in any of the filenames that should be deleted.

rm !(textfile.txt|backup.tar.gz|script.php|database.sql|info.txt) 

The extglob (Extended Pattern Matching) needs to be enabled in BASH (if it’s not enabled):

I get «syntax error near unexpected token `(‘» when I do shopt -s extglob; rm -rf !(README|LICENSE) . Any idea why?

Читайте также:  100 самоучитель linux дж валади

This is the best solution for me and it works by default on my Ubuntu 12.04.4 LTS with no need for shopt

@nic, @Dennis: The syntax error suggests that something OTHER than bash was used, e.g., dash , where extglob is not supported. However, in an interactive bash shell, the command will ALSO not work as stated, though for different reasons. The short of it: execute shopt -s extglob BY ITSELF; ONCE SUCCESSFULLY ENABLED (verify with shopt extglob ), execute rm -rf !(README|LICENSE) . (While extglob is not yet enabled, !(. ) is evaluated by history expansion BEFORE the commands are executed; since this likely fails, NEITHER command is executed, and extglob is never turned on.)

@nic, @Dennis, @mklement0: I had the same issue with «syntax error near unexpected token (» when executing the command within a .sh file (#! /bin/bash) but not when I was running it in a command line interface. It turned out that in addition to the shopt -s extglob run in the command line interface, I had to rerun it inside my script file. This solved the problem for me.

find . | grep -v «excluded files criteria» | xargs rm

This will list all files in current directory, then list all those that don’t match your criteria (beware of it matching directory names) and then remove them.

Update: based on your edit, if you really want to delete everything from current directory except files you listed, this can be used:

mkdir /tmp_backup && mv textfile.txt backup.tar.gz script.php database.sql info.txt /tmp_backup/ && rm -r && mv /tmp_backup/* . && rmdir /tmp_backup 

It will create a backup directory /tmp_backup (you’ve got root privileges, right?), move files you listed to that directory, delete recursively everything in current directory (you know that you’re in the right directory, do you?), move back to current directory everything from /tmp_backup and finally, delete /tmp_backup .

Читайте также:  Как запустить grub linux

I choose the backup directory to be in root, because if you’re trying to delete everything recursively from root, your system will have big problems.

Surely there are more elegant ways to do this, but this one is pretty straightforward.

Источник

Как удалить все файлы в папке Linux

Время от времени стоит чистить систему, чтобы она не засорялась ненужными данными. В случае с дистрибутивами Linux есть несколько способов удаления файлов, применимых в разных ситуациях.

Из данной статьи вы узнаете, как удалить все файлы в папке Ubuntu, в том числе скрытые и не скрытые. Заодно мы разберем важные нюансы данной процедуры, упомянув несколько способов чистки.

Как удалить все файлы в папке Linux

Многие действия в данной операционной системе удобно выполнять с помощью команд в терминале. Чистка содержимого папок тоже относится к их числу. Для начала предлагаем посмотреть полный список файлов в конкретном каталоге, на примере ~/Downloads:

find ~/Downloads -maxdepth 1 -type f

WDS53SE3p2fPeNb3+f64hJQU5y2WzAAAAAElFTkSuQmCC

Файлы, название которых начинается с точки, являются скрытыми. Остальные – не скрытые. Простая чистка не скрытых файлов внутри директории осуществляется такой командой:

KzQAAAABJRU5ErkJggg==

Чтобы стереть все файлы, даже скрытые, выполните эту команду:

p7ceCC3TODQAAAABJRU5ErkJggg==

Для просмотра всех файлов и каталогов в выбранном местоположении, в том числе и скрытых, подойдет команда find без параметров. Например:

Pxc+PyGgnnu4AAAAAElFTkSuQmCC

Полная чистка директории со всеми вложенными файлами и папками (даже скрытыми) осуществляется другой командой:

Похожие записи

Оцените статью

Статья распространяется под лицензией Creative Commons ShareAlike 4.0 при копировании материала ссылка на источник обязательна .

Об авторе

6 комментариев к “Как удалить все файлы в папке Linux”

Спасибо за статью. А как можно настроить, что при запуске команды «rm -rf » данные не удалялись напрямую, а складывались во временную папку или в корзину, как сделано в Windows? Чтобы я потом сам удалял из корзины, после того, как убедился что ничего не поломалось после удаления. Ответить

Читайте также:  Os name and version in linux

Осознаю, не панацея. Но если устроит, то создайте такой скрипт: #!/usr/bin/bash TRASH=»/home/$USER/.trash/» if [ ! -d $TRASH ] ; then
# echo $TRASH
mkdir -p $TRASH
fi for file in $*
do
if [ -f $file ] ; then
# echo $file
mv $file $TRASH
fi
done Назовите его rm и поместите в директорий, в котором находятся Ваши личные запускаемые файлы и скрипты. У меня Debian/MATE. Такой директорий находится в домашнем директории и называется bin. Кроме того, путь к этому поддиректорию у меня задаётся в файле .bashrc. И этот путь размещён раньше пути к директорию /usr/bin/, где находится сстемная утилита rm. Таким образом при выполнении команды rm будет «срабатывать» Ваш скрип, а не системная утилита. И да! После создания скрипта не забудьте сделать его исполняемым — chmod +x. В скрипте я оставил пару команд echo. Это на тот случай, если Вам захочется с ним поиграться. Просто закомментируйте команды mkdir и mv и удалите комментарий у рядом стоящих команд echo. Ответить

Можно просто использовать gio trash: Usage:
gio trash [OPTION…] [LOCATION…] Move/Restore files or directories to the trash. Options:
-f, —force Ignore nonexistent files, never prompt
—empty Empty the trash
—list List files in the trash with their original locations
—restore Restore a file from trash to its original location (possibly recreating the directory) Note: for —restore switch, if the original location of the trashed file
already exists, it will not be overwritten unless —force is set. Ответить

Не буду даже пробовать такое. С самого начала следовало бы написать, насколько это безопасно и почему (и какие) файлы должны быть удалены из системы. Ответить

Источник

Оцените статью
Adblock
detector