1

I have the following command which renames a number of files found by the find command by adding the suffix "processed". How would I modify this to also add a prefix like "ren" ?

find . -type f -name 'file*.dat' -execdir mv {} {}_processed ';'
  • find . -type f -name 'file*.dat' -execdir mv "{}" "ren_{}" \;. – DopeGhoti Jun 6 '17 at 19:04
  • 1
    @DopeGhoti this won't work because find results has full path format. – mkc Jun 6 '17 at 19:07
  • @Ketan, well, depends. GNU find adds ./ to the front even with -execdir, the (probably ancient) BSD find on macOS doesn't. – ilkkachu Jun 6 '17 at 19:11
  • Oh, of course. use "ren_$(basename {})" perhaps? – DopeGhoti Jun 6 '17 at 19:11
  • at least with GNU find you could do -execdir sh -c 'for f; do mv -- "$f" "ren_${f##*/}"; done' sh {} + – steeldriver Jun 6 '17 at 21:51
2

Consider using rename command (based on Perl expression):

find . -type f -name "file*.dat" -execdir rename 's/(file.*?\.dat)$/ren_$1_processed/' {} +

Note the rename regex needs to be lazy lest it catches a file in the directory portion. Plus, rename can happily take multiple arguments.

This will rename all files provided by find command adding prefix ren_ and suffix _processed on both sides of the "base" file name

  • Also note that as written, it wouldn't rename a $'file\n.dat' file (you'd need to add the s flag for . to match the newline) – Stéphane Chazelas Jun 7 '17 at 10:36
  • @StéphaneChazelas, your approach rename '$_ = "ren_${_}_processed"' will not work because of "full path format". You'll get something like Can't rename ./file2.dat ren_./file2.dat_processed: No such file or directory. You should have known that having over 210K reputation – RomanPerekhrest Jun 7 '17 at 10:40
  • Right, it's true that some find implementations include the ./ prefix with -execdir while some others don't (I knew it indeed but overlooked it here, sorry) – Stéphane Chazelas Jun 7 '17 at 11:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.