sábado, junho 03, 2017

How to rename or remove multiple files using find in linux

The following is a direct fix of your approach:
find . -type f -name 'file*' -exec sh -c 'x="{}"; mv "$x" "${x}_renamed"' \;
However, this is very expensive if you have lots of matching files, because you start a fresh shell (that executes a mv) for each match. And if you have funny characters in any file name, this will explode. A more efficient and secure approach is this:
find . -type f -name 'file*' -print0 | xargs --null -I{} mv {} {}_renamed
It also has the benefit of working with strangely named files. If find supports it, this can be reduced to
find . -type f -name 'file*' -exec mv {} {}_renamed \;
The xargs version is useful when not using {}, as in
find .... -print0 | xargs --null rm
Here rm gets called once (or with lots of files several times), but not for every file.
I removed the basename in you question, because it is probably wrong: you would move foo/bar/file8 to file8_renamed, not foo/bar/file8_renamed.
Edits (as suggested in comments):
  • Added shortened find without xargs
  • Added security sticker

find . -type f -name 'file*' -execdir mv {} {}_renamed ';'
find . -type f -name 'file*' -exec rm -v {} \;

Nenhum comentário: