user3365834 user3365834 - 1 year ago 186
Linux Question

Linux, rename files with bash 'no such file or directory' error

I'm trying to add a prefix to all files that are not

files in the current directory, and all subdirectories, with

The problem is that I get an error:

mv: cannot move './test.txt' to 'PRE_./test.txt': No such file or directory

My one-liner is:

find -type f ! -name "*.sh" -exec sh -c 'mv "{}" PRE_"{}"' _ {} \;

I tried
, too:

find -type f ! -name "*.sh" -print0 | xargs -0 rename 's/(.*)$/PRE_$1/'

But I got the same error.
What's wrong?
Thanks in advance!

Answer Source
find -type f ! -name "*.sh" -exec rename -n 's|.*/\K|PRE_|' {} +
  • .*/ matches upto last / in file name
  • by using \K lookbehind, we can avoid need of capture group in this case

Remove -n option from rename once it shows correct renaming

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download