Home > Back-end >  bash, delete all files with a pattern name
bash, delete all files with a pattern name

Time:02-04

  • I need to delete all files with a pattern name:  2020*.js
  • Inside a specific directory: server/db/migrations/
  • And then show what it have been deleted: `| xargs``

I'm trying this:

find . -name 'server/db/migrations/2020*.js' #-delete | xargs

But nothing is deleted, and shows nothing.

What I'm doing wrong?

CodePudding user response:

The immediate problem is that -name only looks at the last component of the file name (so 2020xxx.js) and cannot match anything with a slash in it. You can use the -path predicate but the correct solution is to simply delete these files directly:

rm -v server/db/migrations/2020*.js

The find command is useful when you need to traverse subdirectories.

Also, piping the output from find to xargs does not do anything useful; if find prints the names by itself, xargs does not add any value, and if it doesn't, well, xargs can't do anything with an empty input.

If indeed you want to traverse subdirectories, try

find server/db/migrations/ -type f -name '2020*.js' -print -delete

If your shell supports ** you could equally use

rm -v server/db/migrations/**/2020*.js

which however has a robustness problem if there can be very many matching files (you get "command line too long"). In that scenario, probably fall back to find after all.

CodePudding user response:

You're looking for something like this:

find server/db/migrations -type f -name '2020*.js' -delete -print

CodePudding user response:

You have try this:

find . -name 'server/db/migrations/2020*.js' | xargs rm
  •  Tags:  
  • bash
  • Related