Linux empty deleted files

How can I recursively delete all empty files and directories in Linux?

How can I recursively cleanup all empty files and directories in a parent directory? Let’s say I have this directory structure:

Parent/ |____Child1/ |______ file11.txt (empty) |______ Dir1/ (empty) |____Child2/ |_______ file21.txt |_______ file22.txt (empty) |____ file1.txt 
Parent/ |____Child2/ |_______ file21.txt |____ file1.txt 

I wasn’t confused, per se, but, even before I saw the comments, I thought it was confusing that the illustration had multiple files with the same name. You might want to consider using a naming convention like Child1/file11.txt , Child2/file21.txt and Child2/file22.txt .

3 Answers 3

This is a really simple one liner:

It’s fairly self explanatory. Although when I checked I was surprised that it successfully deletes Parent/Child1. Usually you would expect it to process the parent before the child unless you specify -depth .

This works because -delete implies -depth . See the GNU find manual:

-delete Delete files; true if removal succeeded. If the removal failed, an error message is issued. If -delete fails, find’s exit status will be nonzero (when it eventually exits). Use of -delete automatically turns on the -depth option.

Note these features are not part of the Posix Standard, but most likely will be there under many Linux Distribution. You may have a specific problem with smaller ones such as Alpine Linux as they are based on Busybox which doesn’t support -empty .

Other systems that do include non-standard -empty and -delete include BSD and OSX but apparently not AIX.

Источник

Удаляем пустые файлы и директории

Рассмотрим, как удалить все пустые файлы или директории в определенной директории. Сделать это очень просто через командную строку, используя команды find, rm и rmdir.

Откройте терминал (командную строку) и перейдите командой cd в ту директорию, в которой вам необходимо удалить пустые файлы:

Удаляем пустые файлы

Выведем список пустых файлов. Для этого выполним команду find и укажем ей, что нам в текущей директории необходимо найти только файлы (параметр -type f) и эти файлы должны быть пустыми (параметр -empty):

Теперь воспользуемся аргументом -exec, который позволяет выполнить определенную команду над списком файлов. Мы укажем, что хотим выполнить команду rm (удалить файл). Итак, чтобы удалить пустые файлы выполните команду:

find . -type f -empty -exec rm <> \;

Удаляем пустые директории

Сначала просто посмотрим, какие директории у нас не содержат файлов. Для этого, так же как и для файлов используем команду find с ключом -empty, но указываем -type d. Выполним в командной строке:

Читайте также:  Advanced programing in linux

Получим список пустых директорий.

Теперь нам нужно их удалить. Аргументу -exec укажем команду rmdir (удалить директори). Чтобы удалить пустые директории выполняем:

find . -type d -empty -exec rmdir <> \;

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

Дополнительную информацию по команде find вы можете почитать в статье Команда find: широкие возможности для поиска файлов в Linux.

Источник

How delete all the empty files in linux irrespective of their directory using rm command

I have a lot of empty files in various sub directories of my Linux file system. How can I delete only empty files using the rm command? I’m tired of deleting by going to all the directories and finding the empty files to manually delete, so I’ve found a combination of commands like find -size 0 -type f | rm -f . But I need to delete all the empty files in all the directories, is that possible using only the one rm command?

You can not do with rm alone. I will use find /path/to/dir -empty -type f -delete if I am in your shoes

Do not forget that -delete goes last (otherwise it will start deleting at the point in the find expression where -delete appears)

2 Answers 2

I don’t think rm allows selecting file on the basis of their size. However, if you want to use just one command, you can use find

find /path/to/dir -type f -empty -delete 

-type f is necessary because also directories are marked to be of size zero. And -delete should go at last.

However you may be wanting to delete all files irrespective of their directory, it is not advisable to do so, because there are many system files and some symlinks also which might be deleted in the process.

tested. This should be what you are looking for. I was looking for similar commands a while back and I had this but mine uses xargs.

Running find / -type f -empty -delete might have bad impact as it will remove all empty which which services also depends. Hence, you need to select the path, instead of / path

@dlmeetei is correct! And although you may be wanting to delete all empty files irrespective of their directory, there are many important files and possibly some symlinks also which might get deleted in the process. It would be better if you select the directory yourself.

Читайте также:  Linux ubuntu иконки папок

Well, rm(1) command only deletes the files whose names you pass to it on the command line. There’s no code in rm(1) to allow you to filter those files, based on some condition or criteria. The old UNIX filosophy mandates here, write simple tools and couple them on pipes as neccessary to construct complex commands. In this case, find(1) is the answer. this is a tool to select files based on quite arbitrary criteria (like the one you ask for) and generate the actual file names or simply call commands based on that. On this respect

find dir1 dir2 . -type f -size 0 -print | xargs rm 

would be the solution (batching the filenames with xargs(1) command to do less fork(2) and exec(2) calls with less process fork overhead) to your problem, allowing to specify several dirs, selecting only files of size 0 and passing them to the batch command xargs(1) to erase them in groups. you can even filter the filenames based on some regular expression with

find dir1 dir2 . -type f -size 0 -print | grep 'someRegularExpression' | xargs rm 

and you’ll get erased only the files that match the regular expression (and the other two predicates you expressed in find(1) ) You can even get a list of the erased files with

find dir1 dir2 . -type f -size 0 -print | grep 'someRegularExpression' | tee erased.txt | xargs rm 

See find(1) , grep(1) , tee(1) , xargs(1) and rm(1) for reference.

Источник

How do I remove all empty files out of my directory?

I accidentally pasted into shell and created a bunch of empty files that are all named random numbers. What is an effective way to remove all of these at once? There are other files in the directory that I need; they contain numbers in them but any file in there that starts with a number is bad. Can you like regex delete?

4 Answers 4

You are saying that the files you want to delete are empty. A way to delete those files would be to delete only empty files. In that way, you will not delete a file with any content. I believe this is safer than classifying them by name. A command to delete empty files from the current directory would be:

Stéphane Chazelas contributed constructive comment. A better command would be:

find ./ -maxdepth 1 -type f -size 0 -delete 

That also removes empty files (of any type, including directories as long as they’re empty) in subdirectories recursively. Note that -delete is a non-standard extension (from BSD, also found in GNU’s).

Thanks for the comment, but I tried to make an empty directory and it was not found by the find command.

Читайте также:  Проверить есть ли интернет linux

that directory would also need to be of size 0. On some filesystems like ext4, it’s not possible to have directories of size 0.

Would remove the regular ( . ) non-hidden empty files (of L ength 0).

To remove files¹ whose name is made of only ASCII decimal digits:

Where is to match numbers in a range but with no bound. Again, with other shells, you can use zsh -c ‘. ‘ .

In bash , you could also do:

(shopt -s extglob failglob; rm -f +([0123456789]) 

You can combine the two (remove all-numeric empty regular files) with:

With the POSIX shell and utilities, the equivalent would be:

LC_ALL=C find . ! -name . -prune -type f -size 0c \ ! -name '*[!0-9]*' -exec rm -f <> + 

To find all-numeric files, we find all files except those that contain at least one non-digit. -size 0c matches files whose size in bytes² is 0.

LC_ALL=C makes sure the 0-9 range only includes 0123456789, but also and maybe more importantly for that command to work properly if there are filenames encoded in a charset different from that of the locale. For instance, without it, with GNU find and in a UTF-8 locale, a file called $’St\xe9phane’ ( Stéphane encoded in latin1) would be deleted, not because non-digits can’t be found in it (it’s only made of non-digits), but because it contains that 0xe9 byte that can’t be decoded into a character, so * (which matches 0 or more characters) would fail to match.

zsh globs don’t have the problem, as bytes not forming part of characters are treated as some form of special characters, while with bash globs and with current versions, bash switches to byte-wise matching when input strings can’t be decoded into characters (making it behave as if in the C locale).

¹ this time not limited to regular files, also including symlinks, fifos. Files of type directory would not be deleted however as rm won’t delete directories unless you pass the -r option.

² You could also use -size 0 (whose size in 512-byte units is 0), which would also work here as sizes are rounded up so a file of size one byte would be considered to be made of one 512-byte unit as far as -size 0 is concerned, but more generally, for exact size match, I would recommend using that c suffix as -size 1 for instance is not for files of size 512, but for files of size 1 to 512. Use -size 512c for files whose size is exactly 512. For zsh ‘s L glob qualifier, the default unit is byte, not 512-byte unit.

Источник

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