[Golang] Retaining Specific Folders and Removing the Rest under A Target Path

Let’s consider a situation where there are multiple folders located under a specific path, and we only have the names of a few folders that we want to retain while removing the rest.

For instance, the folder structure is presented below, with all entries being folders:

├── 123123
├── 123456
├── 123678
├── 123789
├── target-folder-1
└── target-folder-2

To tackle this scenario, we can approach it in two logical ways:

  1. Firstly, we can move the known folders to a different folder at the same level as the target path, as a temporary measure. Then, we can delete the target path and rename the temporary folder to match the path name.
  2. Alternatively, we can traverse through the target path and eliminate all folders except those we intend to keep.

In this post, I will demonstrate how to implement the second method using Golang.

func RemoveFoldersNotIncluded(root string, pathsToBeKept []string) error {
	foldersToBeRemoved := []string{}
	err := filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error {
		if err != nil {
			return err
		}

		if !d.IsDir() {
			return nil
		}

		if path == root {
			return nil
		}

		for _, p := range pathsToBeKept {
			if path == p {
				return filepath.SkipDir
			}
		}

		foldersToBeRemoved = append(foldersToBeRemoved, path)
		return nil
	})
	if err != nil {
		return err
	}

	for _, path := range foldersToBeRemoved {
		err = os.RemoveAll(path)
		if err != nil {
			return err
		}
	}
	return nil
}

💡Line 8-9: Only the “dir” object is checked. 💡Line 12-14: The initial object to be visited is always the target path “root,” so we can skip it. It is important not to utilize filepath.SkipDir in this case since it would cause the entire walk function to terminate. 💡Line 16-20: If the current visiting path is included in the list of expected folders, we can skip the directory and move on to the next one. Here, we can employ filepath.SkipDir since it is unnecessary to traverse its subdirectories if we want to retain it.


If this post helped you to solve a problem or provided you with new insights, please upvote it and share your experience in the comments below. Your comments can help others who may be facing similar challenges. Thank you!
Buy Me A Coffee
DigitalOcean Referral Badge
Sign up to get $200, 60-day account credit !