- Linux / Unix: Find and Delete All Empty Directories & Files
- Method # 1: Find and delete everything with find command only
- Delete empty directories
- Delete empty files
- How to count all empty files or directories?
- Method # 2: Find and delete everything using xargs and rm/rmdir command
- Удаляем пустые файлы и директории
- Удаляем пустые файлы
- Удаляем пустые директории
- Linux / UNIX: How To Empty Directory
- How To Empty Directory In Linux and Unix
- Linux Empty Directory Using the rm Command
- Delete All Files Using the Find Command
- How to remove a full directory and all files in Linux
- Conclusion
- linux-notes.org
- Удалить пустые файлы и директории в Unix/Linux
- Удалить пустые файлы в Unix/Linux
- Удалить пустые директории в Unix/Linux
- 5 Ways to Empty or Delete a Large File Content in Linux
- 1. Empty File Content by Redirecting to Null
- 2. Empty File Using ‘true’ Command Redirection
- 3. Empty File Using cat/cp/dd utilities with /dev/null
- 4. Empty File Using echo Command
- 5. Empty File Using truncate Command
- If You Appreciate What We Do Here On TecMint, You Should Consider:
Linux / Unix: Find and Delete All Empty Directories & Files
H ow do I find out all empty files and directories on a Linux / Apple OS X / BSD / Unix-like operating systems and delete them in a single pass?
You need to use the combination of find and rm command. [donotprint]
Tutorial details | |
---|---|
Difficulty level | Easy |
Root privileges | No |
Requirements | find command |
Est. reading time | 5m |
[/donotprint]GNU/find has an option to delete files with -delete option. Please note that Unix / Linux filenames can contain blanks and newlines, this default behaviour is often problematic; filenames containing blanks and/or newlines are incorrectly processed by many utilities including rm command. To avoid problems you need to pass the -print0 option to find command and pass the -0 option to xargs command, which prevents such problems.
Method # 1: Find and delete everything with find command only
The syntax is as follows to find and delete all empty directories using BSD or GNU find command:
Find and delete all empty files:
Delete empty directories
In this example, delete empty directories from
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
Delete empty files
In this example, delete empty files from
Fig.01: Delete empty directories and files.
How to count all empty files or directories?
The syntax is as follows:
- -empty : Only find empty files and make sure it is a regular file or a directory.
- -type d : Only match directories.
- -type f : Only match files.
- -delete : Delete files. Always put -delete option at the end of find command as find command line is evaluated as an expression, so putting -delete first will make find try to delete everything below the starting points you specified.
This is useful when you need to clean up empty directories and files in a single command.
Method # 2: Find and delete everything using xargs and rm/rmdir command
The syntax is as follows to find and delete all empty directories using xargs command:
Источник
Удаляем пустые файлы и директории
Рассмотрим, как удалить все пустые файлы или директории в определенной директории. Сделать это очень просто через командную строку, используя команды find, rm и rmdir.
Откройте терминал (командную строку) и перейдите командой cd в ту директорию, в которой вам необходимо удалить пустые файлы:
Удаляем пустые файлы
Выведем список пустых файлов. Для этого выполним команду find и укажем ей, что нам в текущей директории необходимо найти только файлы (параметр -type f) и эти файлы должны быть пустыми (параметр -empty):
Теперь воспользуемся аргументом -exec, который позволяет выполнить определенную команду над списком файлов. Мы укажем, что хотим выполнить команду rm (удалить файл). Итак, чтобы удалить пустые файлы выполните команду:
Удаляем пустые директории
Сначала просто посмотрим, какие директории у нас не содержат файлов. Для этого, так же как и для файлов используем команду find с ключом -empty, но указываем -type d. Выполним в командной строке:
Получим список пустых директорий.
Теперь нам нужно их удалить. Аргументу -exec укажем команду rmdir (удалить директори). Чтобы удалить пустые директории выполняем:
Обращаю ваше внимание на то, что выполнять данные команды нужно с осторожностью, чтобы случайно не удалить то, что не нужно. Также нельзя выполнять их в системных директориях, так как в большинстве случаев пустые файлы и директории созданы там специально, и их отсутствие приведет к сбоям в системе.
Дополнительную информацию по команде find вы можете почитать в статье Команда find: широкие возможности для поиска файлов в Linux.
Источник
Linux / UNIX: How To Empty Directory
How To Empty Directory In Linux and Unix
- rm command – Delete one or more files or directories.
- find command – Find and delete all files from a specific directory.
Linux Empty Directory Using the rm Command
First, consider the following directory structure displayed using the tree command
To delete all files from /tmp/foo/ directory (i.e. empty /tmp/foo/ directory), enter:
$ cd /tmp/foo/
$ rm *
OR
$ rm /tmp/foo/*
Delete All Files Using the Find Command
Consider the following directory structure:
To delete all files from /tmp/bar/ directory (including all files from sub-directories such as /tmp/bar/dir1), enter:
$ cd /tmp/bar/
$ find . -type f -delete
OR
$ find /tmp/bar/ -type f -delete
The above find command will delete all files from /tmp/bar/ directory. It will not delete any sub-directories. To remove both files and directories, try:
find /path/to/target/dir/ -delete
The find commands options are as follows:
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
- -type f : Delete on files only.
- -type d : Remove folders only.
- -delete : Delete all files from given directory name.
How to remove a full directory and all files in Linux
To remove a directory that contains other files or sub-directories, use the following rm command command. In the example, I am going to empty directory named “docs” using the rm -rf command as follows:
rm -rf /tmp/docs/*
Get verbose outputs:
rm -rfv /tmp/docs/*
The rm command options are as follows:
- -r : Delete directories and their contents recursively on Linux or Unix-like systems.
- -f : Forceful removal. In other words, ignore nonexistent files and delete whatever found.
- -v : Verbose outputs. For example, explain what is being done on screen.
Conclusion
You learned how to use the rm and find command to delete all files and sub-directories on Linux/macOS/*BSD and Unix-like systems. In other words, this is useful to empty folders on Linux. For more information see rm command help page here.
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Источник
linux-notes.org
Удалить пустые файлы и директории в Unix/Linux
Решил написать статью о там как можно удалить пустые файлы и директории в ОС — Linux. Я покажу и расскажу как это можно сделать в своей статье «Удалить пустые файлы и директории в Linux» и приведу готовые примеры как можно удалить все пустые файлы или директории в определенной папке. Делается это через командную строку с использованием команд: find, rm и rmdir.
Сейчас откроем терминал (командную строку) и перейдем в ту папку, в которой вам нужно удалить все пустые файлы:
Удалить пустые файлы в Unix/Linux
Для начала, посмотрим список имеющихся пустых файлов. Для этого, я буду использовать команду find и укажу ей (передам параметр), что мне нужно найти только файлы (за это отвечает параметр «-type f») и что данные файлы должны быть пустыми (за это отвечает параметр «-empty») в текущей моей папки:
Теперь, я воспользуюсь аргументом «-exec», он дает возможность выполнить определенную команду над списком файлов. Я передам в «exec» то, что хочу выполнить команду «rm» (удалить файлы) для пустых файлов:
Удалить пустые директории в Unix/Linux
Для начала, я проверю какие папки у меня не содержат файлов. Для этого, я так же буду использовать команду «find» с параметром «-empty», но указываю тип поиска «-type d» (поиск папок):
Сейчас мне необходимо их удалить. Передаю аргументу «-exec» команду rmdir (удаление папок) для того чтобы удалить все имеющиеся пустые папки:
Еще можно использовать:
Или еще по-простому:
Статья «Удалить пустые файлы и директории в Unix/Linux» подошла к завершению.
Источник
5 Ways to Empty or Delete a Large File Content in Linux
Occasionally, while dealing with files in Linux terminal, you may want to clear the content of a file without necessarily opening it using any Linux command line editors. How can this be achieved? In this article, we will go through several different ways of emptying file content with the help of some useful commands.
Caution: Before we proceed to looking at the various ways, note that because in Linux everything is a file, you must always make sure that the file(s) you are emptying are not important user or system files. Clearing the content of a critical system or configuration file could lead to a fatal application/system error or failure.
With that said, below are means of clearing file content from the command line.
Important: For the purpose of this article, we’ve used file access.log in the following examples.
1. Empty File Content by Redirecting to Null
A easiest way to empty or blank a file content using shell redirect null (non-existent object) to the file as below:
Empty Large File Using Null Redirect in Linux
2. Empty File Using ‘true’ Command Redirection
Here we will use a symbol : is a shell built-in command that is essence equivalent to the true command and it can be used as a no-op (no operation).
Another method is to redirect the output of : or true built-in command to the file like so:
Empty Large File Using Linux Commands
3. Empty File Using cat/cp/dd utilities with /dev/null
In Linux, the null device is basically utilized for discarding of unwanted output streams of a process, or else as a suitable empty file for input streams. This is normally done by redirection mechanism.
And the /dev/null device file is therefore a special file that writes-off (removes) any input sent to it or its output is same as that of an empty file.
Additionally, you can empty contents of a file by redirecting output of /dev/null to it (file) as input using cat command:
Empty File Using cat Command
Next, we will use cp command to blank a file content as shown.
Empty File Content Using cp Command
In the following command, if means the input file and of refers to the output file.
Empty File Content Using dd Command
4. Empty File Using echo Command
Here, you can use an echo command with an empty string and redirect it to the file as follows:
Empty File Using echo Command
Note: You should keep in mind that an empty string is not the same as null. A string is already an object much as it may be empty while null simply means non-existence of an object.
For this reason, when you redirect the out of the echo command above into the file, and view the file contents using the cat command, is prints an empty line (empty string).
To send a null output to the file, use the flag -n which tells echo to not output the trailing newline that leads to the empty line produced in the previous command.
Empty File Using Null Redirect
5. Empty File Using truncate Command
The truncate command helps to shrink or extend the size of a file to a defined size.
You can employ it with the -s option that specifies the file size. To empty a file content, use a size of 0 (zero) as in the next command:
Truncate File Content in Linux
That’s it for now, in this article we have covered multiple methods of clearing or emptying file content using simple command line utilities and shell redirection mechanism.
These are not probably the only available practical ways of doing this, so you can also tell us about any other methods not mentioned in this guide via the feedback section below.
If You Appreciate What We Do Here On TecMint, You Should Consider:
TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.
If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.
We are thankful for your never ending support.
Источник