I need to rename all files with .js extension, but names of files can vary, for example:

rootDirectory
--firstDirectory
----first.js
--secondFileDirectory
----second.js
--thirdDirectory
----third.js

Needs to be renamed to

rootDirectory
--firstDirectory
----newName.js
--secondFileDirectory
----newName.js
--thirdDirectory
----newName.js

Is there a way to do it?

I'm using Ubuntu 14.04

  • What operating system and version are you using? – Stephen Harris Aug 19 '16 at 14:18
  • @StephenHarris Harris Ubuntu 14.04 – snowfinch27 Aug 19 '16 at 14:19
up vote 4 down vote accepted

Ububtu 14 has a version of find that has the -execdir option, so this becomes relatively simple:

find . -name '*.js' -execdir mv -i {} newName.js \;

For example, I have this tree:

./A
./A/first.js
./B
./B/second.js

I run the command

$ find . -name '*.js' -execdir mv -i {} newName.js \;

The resulting tree:

./A
./A/newName.js
./B
./B/newName.js

Based on Perl rename, assumes pwd is rootDirectory:

rename 's|(.*/).*\.js|$1newName.js|' */*

or

rename 's|.*/\K.*\.js|newName.js|' */*
  • use rename -n if you want to check how the renaming will happen

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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