UNIX / Linux: Deleting Multiple Files In Bulk

How do delete multiple files in bulk (say all *.bak file stored in /netapp/ and its sub-directory) under Linux / UNIX / *BSD MacOS X operating systems?

You can use the find command as follows to find and delete file in bulk.

Find command

The syntax is:

find /path/to/delete -type f -iname "fileType" -delete

OR

find /path/to/delete -type f -iname "fileType" -exec rm -f {} \;

To delete all *.bak files in bulk from /netapp/ and its sub-directory, enter:
# find /netapp/ -type f -iname "*.bak" -delete
OR
# find /netapp/ -type f -iname "*.bak" -exec rm -f {} \;

Shell scripting example to delete files in bulk

In this example, I have a file called delete.txt (with 5000+ entries, each per line) and you need to delete all those files:

/netapp/one.txt
/netapp/dir2/one.txt
/netapp/dir1/dir500/one.txt
....
...
....
/netapp/fivek.txt

Create a shell script as follows to read a text file using while loop one line at a time:

#!/bin/bash
# Author: Vivek Gite
# Purpose: Delete a file using shell script in bulk
# -------------------------------------------------- 
## SET ME FIRST ##
_input="/path/to/delete.txt"
 
## No editing below ##
[ ! -f "$_input" ] && { echo "File ${_input} not found."; exit 1; }
while IFS= read -r line
do 
	[ -f "$line" ] && rm -f "$line"
done < "${_input}"

Run it as follows:
$ chmod +x script.sh
$ ./script.sh

The while statement is used to executes rm commands repeatedly on each file.


🐧 Get the latest tutorials on Linux, Open Source & DevOps via RSS feed or Weekly email newsletter.

🐧 0 comments... add one


CategoryList of Unix and Linux commands
Disk space analyzersdf duf ncdu pydf
File Managementcat cp mkdir tree
FirewallAlpine Awall CentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Modern utilitiesbat exa
Network UtilitiesNetHogs dig host ip nmap
OpenVPNCentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Managerapk apt
Processes Managementbg chroot cron disown fg glances gtop jobs killall kill pidof pstree pwdx time vtop
Searchingag grep whereis which
User Informationgroups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPNAlpine CentOS 8 Debian 10 Firewall Ubuntu 20.04
0 comments… add one

Leave a Reply

Your email address will not be published.

Use HTML <pre>...</pre> for code samples. Still have questions? Post it on our forum