- Delete files with specific content
- 2 Answers 2
- How to Remove Files Recursively in Linux
- Deleting all files recursively in Linux
- How to remove files recursively by size
- How to remove files recursively by extension (File type)
- How to delete files recursively based on modification or creation time
- Conclusion
- About the author
- David Adams
- Use rm to Delete Files and Directories on Linux
- The Basics of Using rm to Delete a File
- Options Available for rm
- -i Interactive mode
- -f Force
- -v Verbose
- -d Directory
- -r Recursive
- Combine Options
- -rf Remove Files and Directories, Even if Not Empty
- Combine rm with Other Commands
- Remove Old Files Using find and rm
Delete files with specific content
The output of grep would include the filename and the line containing the string so instead of passing it to rm , it would just run the rm command on * which is everything in the directory and it would delete the files and give an error for directories because the -r switch isn’t used. Do you want to delete the files that have that string in their contents? If so, provide an example of what it might look like. Do you also want to delete files that have Key = 01 or MyKey = 05 ?
2 Answers 2
You can use the following command in the shell. This should do the job if pattern to be searched is Key = 0
grep -lrIZ "Key = 0" . | xargs -0 rm -f --
grep -lrIZ "" . | xargs -0 rm -f --
The main issue with the pipeline using grep + rm is that rm does not read from its standard input stream, which means that it does not read anything from the grep command on the left-hand side of the pipe.
Instead, the rm * on the right-hand side of the pipe would ignore all input and execute rm on every visible filename in the current directory.
Ignoring the issue with rm not reading its standard input, your grep command has two main issues:
- It outputs matching lines with filenames. This would be of no use to rm as we need to know only the filenames of the files we want to delete.
- It matches Key = 0 as a substring, which means it also matches Crypto Key = 0x01 etc.
find . -type f -exec grep -q -F -x 'Key = 0' <> \; -exec rm -f <> +
or, with GNU find (and some others),
find . -type f -exec grep -q -F -x 'Key = 0' <> \; -delete
Both of these would look for regular files in the current directory or below, and for each found file, it would execute grep -q -F -x ‘Key = 0’ . This grep command would return an exit status signalling whether there is a line in the file that is exactly Key = 0 (and nothing else).
The second find command will delete the file using its -delete predicate if such a line is found. The first find command would collect the pathnames of the files containing this line and then run rm -f on batches of these.
The flags used with grep are
- -q , for quiet operation. The utility does not output matching lines but exits successfully after the first match or with a non-zero exit status if the file does not contain a match.
- -F , for fixed string matching. We are matching with a string, not a regular expression.
- -x , to find full-line matches only. This has the same effect as if using a regular expression anchored to both the start and end of the line.
I’m not using -i with grep here as that would also delete files containing lines like KEY = 0 and kEY = 0 etc., and you have said nothing about these case variations.
Would you want the find command to be restricted to a particular filename suffix, like .ext , then use -name ‘*.ext’ in the find command before the execution of grep . For example:
find . -name '*.ext' -type f -exec grep -q -F -x 'Key = 0' <> \; -exec rm -f <> +
How to Remove Files Recursively in Linux
After reading this article, you will be able to find and remove single or multiple files from the command line. This tutorial is optimized for both new and experienced Linux users.
The first section of this tutorial explains how to remove files recursively (directories with all their content and subdirectories’ content). Below I also added instructions to remove recursively certain types of files depending on their size, extension, creation or modification time, and permissions.
All practical examples in this document contain screenshots to make it easy for every Linux user to understand and apply them to their needs.
Deleting all files recursively in Linux
The first section shows how to use the rm (Remove) command to delete a directory with all its content, including all subdirectories with their files and additional subdirectories.
The rm command used with -r flag will remove all directories’ content independently of their type.
But first, let’s see the directories in my home using the ls command.
As you can see, I have 5 directories: Desktop, dir2, Documents, Downloads, and removerecurdir.
Let’s see the content of the directory named removerecurdir using the command tree as shown in the screenshot below.
According to the tree output the removerecurdir directory contains two directories that contain subdirectories and a file inside removecurdir: The directory dir1, with otherdir and otherdir2 subdirectories, and the directory dir2 contains a file named file3.
Let’s say we want to remove the removecurdir and all its content including all files and subdirectories. The proper command is the rm command followed by the -r flag as shown in the syntax below.
Thus, if I want to remove the removerecurdir with all the content, I run:
The subsequent ls output shows the directory, and all its content were successfully removed.
How to remove files recursively by size
This section shows how to recursively delete files smaller than 10 megabytes using the command find.
The syntax is the following:
Note that in the example below, I use sudo to get privileges to remove protected files.
The syntax to remove files greater than a specific size is very similar. The minus (-) symbol must be replaced by a plus symbol (+). The exact syntax is shown below.
In the example below I will use the previous syntax to remove files greater than 1 GB.
How to remove files recursively by extension (File type)
The current chapter explains how to delete files recursively by extension or file type.
On my home I have a directory named testhint. Let’s see its content using the tree command.
As you can see, the parent directory testhint contains a file (file1.txt) and two subdirectories: testhint2 containing file3.txt and the testhint3 subdirectory containing file3 and something.txt.
Let’s assume you want to recursively remove all txt files only. The syntax is the following:
Thus, to remove all txt files recursively within the parent directory testhint, I run the command shown in the figure below.
As you can see all txt files were removed, and only file3 without an extension remains.
You can also delete files by extension using find together with exec commands, as I will explain below.
Let’s see a new scenario with the same directory structure but different files.
The above image shows 4 log files and 3 files without extension.
The syntax to remove files by extensions using -exec is the following:
Thus, to remove the .log files from the previous screenshot, I ran the command below.
The image above shows all .log files were deleted while other files remained.
The xargs command offers the same solution. The difference between xargs and exec is that exec runs the rm function every time a file matches the condition. The command xargs executes the rm command once for all found files matching the condition.
The syntax to remove all files by extension with find and xargs is the following:
The new scenario depicted in the screenshot below shows five .c files in different subdirectories and five files without the .c extension.
To remove all .c files using xargs I run the command as shown below.
Again, you can see the selected extension files were successfully deleted.
Deleting all files recursively based on permissions
Let’s check the new content of the testhint directory.
There are four files with full permissions (file2, file3.c, file6.c and file7).
Now let’s assume you want to find and remove all files with full permissions for everyone.
The syntax is the following:
Thus, to remove all files with full access to all users, I execute the command below.
How to delete files recursively based on modification or creation time
The last section of this tutorial explains how to delete files recursively by creation or modification time.
The syntax is the following:
If you want to delete files created or modified in the last day (last 24 hours), run the following command, where 1 is the number of days, and the minus (-) symbol specifies files created or modified before the defined number of days.
To remove files created or modified before a day, before 24 hours, just replace the minus symbol for a plus symbol.
Conclusion
Since Linux is a very versatile and flexible operating system, users have different techniques to get the same result. All the alternatives explained above are valid for almost every Linux distribution. Some of the commands are even useful for some Unix systems. As you can see, implementing them is easy and any Linux user can do it independently of their knowledge level. To delete files recursively according to other conditions, check the main page of each command described in this article.
About the author
David Adams
David Adams is a System Admin and writer that is focused on open source technologies, security software, and computer systems.
Use rm to Delete Files and Directories on Linux
Estamos traduciendo nuestros guías y tutoriales al Español. Es posible que usted esté viendo una traducción generada automáticamente. Estamos trabajando con traductores profesionales para verificar las traducciones de nuestro sitio web. Este proyecto es un trabajo en curso.
This guide shows how to use rm to remove files, directories, and other content from the command line in Linux.
To avoid creating examples that might remove important files, this Quick Answer uses variations of filename.txt . Adjust each command as needed.
The Basics of Using rm to Delete a File
rm filename1.txt filename2.txt
Options Available for rm
-i Interactive mode
Confirm each file before delete:
-f Force
-v Verbose
Show report of each file removed:
-d Directory
Note: This option only works if the directory is empty. To remove non-empty directories and the files within them, use the r flag.
-r Recursive
Remove a directory and any contents within it:
Combine Options
Options can be combined. For example, to remove all .png files with a prompt before each deletion and a report following each:
remove filename01.png? y filename01.png remove filename02.png? y filename02.png remove filename03.png? y filename03.png remove filename04.png? y filename04.png remove filename05.png? y filename05.png
-rf Remove Files and Directories, Even if Not Empty
Add the f flag to a recursive rm command to skip all confirmation prompts:
Combine rm with Other Commands
Remove Old Files Using find and rm
Combine the find command’s -exec option with rm to find and remove all files older than 28 days old. The files that match are printed on the screen ( -print ):
find filename* -type f -mtime +28 -exec rm '<>' ';' -print
In this command’s syntax, <> is replaced by the find command with all files that it finds, and ; tells find that the command sequence invoked with the -exec option has ended. In particular, -print is an option for find , not the executed rm . <> and ; are both surrounded with single quote marks to protect them from interpretation by the shell.
This page was originally published on Tuesday, July 3, 2018.