DEV Community

Cover image for Linux - Find in Multiple Folders and Delete Files Within
Eyal Lapid
Eyal Lapid

Posted on

Linux - Find in Multiple Folders and Delete Files Within

This is a worknote.

Scenario

In a Javascript monorepo, there was a need to:

  • delete all dist folders files, not the folders themselfs
  • but without touching the .gitignore in the folders

TLDR

dir=$(find ./packages -name "dist" -type d);
Enter fullscreen mode Exit fullscreen mode
for i in $dir; do find $i -type f \( -iname "*" ! -iname ".gitignore" \) -exec rm {} +; done
Enter fullscreen mode Exit fullscreen mode

Solution

  1. Find all dist folders in the monorepo
  2. Iterate over the folders set and collect all files within them, excluding .gitignore
  3. Delete all sets of found files.

Solution Walkthrough

Find all folders with specific name

find ./packages -name "dist" -type d
Enter fullscreen mode Exit fullscreen mode

find - find - find files. Allow filtering.

./packages - target root folder to start the search from.

-name "dist" - filter only object with the name "dist".

-type d - filter only object with type of directory.

Execute Bash Expression

Exectute an expression in bash and put the results in a local variable.

dir=$()
Enter fullscreen mode Exit fullscreen mode

Find all relevant files in a folder

find $i -type f \( -iname "*" ! -iname ".gitignore" \)
Enter fullscreen mode Exit fullscreen mode

$i - Variabe containing the folder name from the for iteration.

-type f - filter object only of type of file.

-iname - From the docs: Like -name, but the match is case insensitive.

! - From the docs: ! expr True if expr is false. This character will also usually need protection from interpretation by the shell.

\( - From the docs: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: \(...\) instead of (...)

for i in $dir; do find $i -type f \( -iname "*" ! -iname ".gitignore" \); done
Enter fullscreen mode Exit fullscreen mode

Run through folders set and execute find on them

for i in $dir; do find $i; done
Enter fullscreen mode Exit fullscreen mode

for - for loop

$i - iteration variable

Execute delete on found set

find $i -exec rm {} +
Enter fullscreen mode Exit fullscreen mode

-exec command {} + - From the docs: his variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end.

The string {} is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find.

Top comments (0)