0

I have a directory tree like this

.
|-- players
|   |-- red_alice.plr
|   |-- red_bob.plr
|-- resources
|   |-- red_cash.rsc
|   |-- red_food.rsc

I want to go through all directories and rename any file that starts with "red" to instead start with "blue"...

I think it is work of find and sed commands but I am not sure how to formulate this situation...I know for example I can find files by

find . -name "red*" -type f

then how to use this output to rename red to blue?

New contributor
DEKKER is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
  • Try find path_to_dir/ -type f -name 'red_*' -exec sh -c 'for f; do echo mv -- "$f" "${f/red/blue}"; done' _ {} + When satisfied, remove the echo part – Valentin Bajrami Jan 10 at 13:21
1

You can do it with rename command:

find . -type f -name "red*" -exec rename  s/red/blue/g "{}" +;

So it will find the files with name starting with red and then will put all of them in single command like

 rename s/red/blue/g red_first red_second

It will search for files in all directories below the current directory.

  • Cool. Didn't know rename. Also has a option -n to print what would be done instead of doing it. – Ralf Jan 10 at 13:34
  • Yeah, just verbose kind. – P_Yadav Jan 10 at 13:35
  • This did not change anything and also did not produce any error message..hmmm – DEKKER yesterday
  • It should work I tried it. – P_Yadav yesterday
0

Maybe like this:

find . -name "red_*" -exec bash -c 'echo mv "{}" "$(echo "{}" | sed "s%/red_%/blue_%" )"' \;

This just prints the commands. Good to check if it would actually work. If you verified that, remove the echo before mv.

  • hmm I get this error 'find missing argument to -exec'' – DEKKER Jan 10 at 12:16
  • Did you also add the \; at the end? – Ralf Jan 10 at 13:25

Your Answer

DEKKER is a new contributor. Be nice, and check out our Code of Conduct.

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.