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?

  • 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. – Prvt_Yadv Jan 10 at 13:35
  • This did not change anything and also did not produce any error message..hmmm – DEKKER Jan 15 at 9:31
  • It should work I tried it. – Prvt_Yadv Jan 15 at 9:37
  • @P_Yadav I think the Linux machine I am working on is quite old and this way is not supported – DEKKER Jan 21 at 13:36
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

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.