Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
December 19, 2021 08:05 am GMT

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);
for i in $dir; do find $i -type f \( -iname "*" ! -iname ".gitignore" \) -exec rm {} +; done

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

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=$()

Find all relevant files in a fo`er

bash
find $i -type f \( -iname "*" ! -iname ".gitignore" \)

$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

Run through folders set and execute find on them

for i in $dir; do find $i; done

for - for loop

$i - iteration variable

Execute delete on found set

find $i -exec rm {} +

-exec - From the docs: Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered.

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.


Original Link: https://dev.to/elpddev/find-in-multiple-folders-and-delete-files-within-4keb

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To