Many times you may need to find and delete all files that fulfill a criteria on your Linux system. Although rm command is used for file & folder deletion, it does not support finding & deleting files based on specific criteria. For such purposes, people use find function with -exec option that allows you to search for files using find command and delete them using rm command. In this case, find command will expand the rm statement for each found file. But this too has a limitation since every Linux system has a limit to the length of commands it supports. Therefore, in such cases, it is advisable to use xargs command with find command. In this article, we will look at how to find & delete files using xargs command.
XARGS Command To Find & Delete Files
xargs command allows you to read input from command line and build them into individual commands. In other words, it allows you to use the output of one command as the input of another command.
Typically, we use the following rm command
rm *.txt or rm file.txt
to delete one or more files, in this case, .txt files. However, the above command works on only your present working directory. What if you want to delete all .txt files on your disk?
You can use it with find function to find all .txt files on your disk.
find / -type f -name '*.txt'
Now if you want to delete these files, you can simply use exec option with rm command as shown below.
find / -type f -name '*.txt' -exec rm -f {} \;
In fact, modern versions of find command provide -delete option to delete files, without having to use exec option
find / -type f -name '*.txt' -delete
If you want to use xargs command to delete these files just pipe it to xargs command with rm function as its argument.
find / -type f -name '*.txt' | xargs rm
In the above case, xargs command will construct separate rm statements for each file name passed to it by the result of find command.
That’s it. In this article, we have covered different ways to find and delete files – using find with exec option, find with delete option and find with xargs. The fastest and most secure way to find and delete files on your system is to use find command with delete option. If that option is not available on your system, you can use find command with xargs.
Also read:
How to Reset Root Password in RHEL/Fedora/CentOS
How to Use Auto Indent in VI Editor
How to Setup LogAnalyzer with Rsyslog and MySQL
How to Setup Rsyslog with MySQL
How to Upload & Download Files from FTP in Linux
Related posts:
Sreeram has more than 10 years of experience in web development, Python, Linux, SQL and database programming.