DEV Community

Alex
Alex

Posted on

How to delete duplicated subdirectories recursively using the terminal

The other day I came across a problem where I had three directories where I had two subdirectories with the same name (target).

Directories problem in terminal

The thing I want to achieve is to delete them in one command, this is the solution I found.

Using the terminal to delete multiple directories.

There is an useful command called find, this command is used to traverse nested directories and evaluate an expression for each element.

We can use find to delete files or directories, here is the command:

find . -type d -name "target" -exec rm -rf {} +
Enter fullscreen mode Exit fullscreen mode

Understanding the command

This command is easy to grasp, first we have ., this is telling find to start traversing in the current directory.

Next we have -type, this argument allows to select a a specific valid file.

The valid files are listed below:

  • b: block special
  • c: character special
  • d: directory
  • f: regular file
  • l: symbolic link
  • p: FIFO
  • s: socket

Since we need to find an specific directory we use d.

Next it's -name, we need to give the string that contains the name we are searching for. In our case we are looking for the directories named "target".

The last part of the command, -exec, is telling what to do once we find a valid element. In this case we want to delete all the found occurrences, so we're passing rm -rf.

The {} is just telling that we need to use the current element's name, and + is used to terminate the -exec part.

Conclusion

By using this simple command we can find and delete subdirectories in an easy and convenient way, which I find to be faster than using the GUI.

I hope this simple tutorial can help you to solve these kind of problems.

Top comments (0)