Linux remove all empty files

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.

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).

Читайте также:  Linux delete all file and directory

¹ 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.

Источник

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Источник

Delete empty files and directories in Linux

We’ll learn how to remove empty directories and empty file on Linux.

Empty directories don’t take up any disk space, but they’re good to keep them tidy. We should clear out old files and folders periodically.

All the instructions in this tutorial are for Linux systems. They won’t work on Windows.

Delete Empty Files in a Directory

You can use the `find` command to remove all the empty files in an existing folder.

$ find . -type f -empty -print -delete

To delete empty directories, we first need to search for all the empty folders in the specified folder and then, delete them.

To find all the empty directories in the current directory, use the following command: find. −type d −empty −print | xargs rm −rf. Add the −delete option to remove them.

Let’s take an example to better explain this concept.

A directory containing both empty and non-empties may be considered. Here, the file prefixed with data-filename is a non-empty file and the one prefixed with empty is an empty file.

|-- data-file1 |-- data-file2 |-- empty-file1 |-- empty-file2 |-- empty-file3 |-- empty file 4 |-- mydir1 | |-- data-file3 | `-- empty-file5 |-- mydir2 | |-- data-file4 | `-- empty-file6 `-- mydir3 `-- mydir4 `-- mydir5

We’ll now run the above command inside these directories. It will delete all empty files recursively — meaning that the empty-file4 and empty-file5 inside the directories mydir1 and mydird2, respectively, will be removed too.

$ find . -type f -empty -print -delete ./empty-file1 ./empty-file2 ./empty-file3 ./mydir1/empty-file5 ./mydir2/empty-file6 ./empty file 4

Let’s look at the output carefully. We’ll see that this operation has removed the files whose names include spaces from the directory.

Читайте также:  Linux find files by contents

It has deleted only empty files and not the directories like mydir1, mydir2, mydir4, and mydir6.

Non-Recursive Deletion of Empty Files

We’ve talked about deleting empty files from directories recursively so far. But what if we want to remove empty files from the current directory itself?

The find utility has an option −maxDepth that defines the maximum depth at which the find utility searches for files.

Using −maxdepth1, the ‘f’ (file) command will search for files in the current directory only.

$ find . -maxdepth 1 -type f -empty -print -delete ./empty-file1 ./empty-file2 ./empty-file3 ./empty file 4

Delete All Empty Directories

We can search for files by using -type f with the find command −

$ find . -type d -empty -print -delete

It will remove all the empty directories from the current directory.

Let’s run this command inside the directory where we saved our script.

$ find . -type d -empty -print -delete ./mydir3 ./mydir4/mydir5 ./mydir4

After deleting the mydir5 folder, mydir3 is no longer an empty directory; instead, it contains the files from mydir2.

Non-Recursive Deletion of Empty Directories

By using −maxdepth 1, the find utility searches only for empty directories in the current working directory.

$ find . -maxdepth 1 -type d -empty -print -delete ./mydir3

Delete Empty Files and Directories Together

It’s now finally the right moment to combine everything that we’ve learned so far. Delete all the empty files and folders from the current directory by running one command.

We’ll use the logical OR (OR) operation (-o), with the find utility, to search for empty files or directories.

$ find . -type d -empty -print -delete -o -type f -empty -print -delete ./empty-file1 ./empty-file2 ./empty-file3 ./mydir1/empty-file5 ./mydir2/empty-file6 ./mydir3 ./mydir4/mydir5 ./mydir4

The −o option splits the command from the filename into two parts. The fist part, −type d −empty − print −delete, deletes all the empty directories, whereas the second part, − type f −empty − print − delete, deletes all the files which are empty.

We can use −maxdepth 0 to delete the empty files/directoires recursively.

$ find . -maxdepth 1 -type d -empty -print -delete -o -type f -empty -print -delete ./empty-file1 ./empty-file2 ./empty-file3 ./mydir3

Conclusion

Here, we’ve learnt about empty files, empty folders, and how to remove them in Linux. We’ve looked at two different ways of deleting files − Recursive and Non−Recursive.

It is important to review all the directories and delete any unnecessary ones before removing them. In all the examples discussed above, we can use the −recurse option to review all the directories that would be removed.

As a best practice, we can set up a cron task to remove empty folders and subfolders from our system. This way, we won’t ever accumulate empty folders and subfoldes on our computer.

Источник

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?

Читайте также:  Astra linux systemd unit

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.

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.

Источник

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