- Published on
Remove All Files/Directories Except for One File Using Unix Commands
2 min read
- Authors
- Name
- Vijaykumar Rajendran
- @karan_6864
Table of Contents
A few weeks ago, one of my friend Honnesh faced a challenge of cleaning up a cluttered directory in my Unix-based system without deleting a crucial configuration file. This led me to use a specific Unix command that allows for selective file deletion while preserving designated files.
Why Would I Need It?
In many scenarios, such as software development or server management, directories can become filled with temporary or redundant files. Cleaning these up manually is not only tedious but also prone to errors. The command discussed here provides a precise, automated approach to maintain cleanliness and order.
HonneshUsing Unix Commands
The Command
find . ! -name 'file.txt' -type f -exec rm -f {} +
How It Works
This command is straightforward yet powerful. Here’s a breakdown:
find .
starts the search in the current directory.! -name 'file.txt'
excludes 'file.txt' from the matched results.-type f
ensures that only files are considered, not directories.-exec rm -f {} +
deletes all files that match the criteria.
Practical Use
Suppose you want to clean up a project directory but keep the main configuration file, file.txt
, intact:
cd /path/to/project
find . ! -name 'file.txt' -type f -exec rm -f {} +
Experiment with Caution!
The power of Unix commands lies in their ability to perform complex tasks with simple syntax. However, with great power comes great responsibility — always ensure to have backups and test extensively.
Happy Coding 🎉