I have folders with multiple files in them. There is an expression in the names that I'd like to change.

For example:

find /path/ -type f -name '*0050ABC_01032013*'

gives me an output like this:


I want to change 0050ABC_01032013 to 0044CBA_01011901.

I have tried this:

find /path/ -type f -name '*0050ABC_01032013*' -execdir rename s/\.\/(w+)0050ABC_01032013(w+)$/$10044CBA_01011901$2/' {} \;

But it's not working. What should I do?

  • 3
    When asking questions, telling us that something "didn't work" is almost useless. Please always explain exactly what happened. How did it fail? What error messages were there? Did it do anything at all? Did it to something but the wrong thing? – terdon Nov 29 '16 at 9:57

rename is not that tricky :) Just specify the part you want to change and the rest will be left alone. Use g to modify all occurrences in the path (including directory names)

find /path/ -type f -name '*0050ABC_01032013*' -exec rename -n 's/0050ABC_01032013/0044CBA_01011901/g' '{}' \;

Remove -n after testing to really rename the files

find /path/ -type f -name '*0050ABC_01032013*' -exec rename 's/0050ABC_01032013/0044CBA_01011901/g' '{}' \;

If you have a directory somewhere in the path with the same name and you do not want to change the directory name, you can make sure only the basename gets modified like this

find /path/ -type f -name '*0050ABC_01032013*' -exec rename -n 's/0050ABC_01032013([^\/]*)$/0044CBA_01011901$1/' '{}' \;

This avoids matching the string if there is a / character anywhere after it.

  • hi, thanks for the answer but it doesn't seem to work: /home/b67-belledone/test_bash_script/0050ROT_01032013/t1mri/T1pre_2013-3-1/y_0050ROT_01032013_inverse.nii.minf renamed as /home/b67-belledone/test_bash_script/0044CBA_01011901/t1mri/T1pre_2013-3-1/y_0050ROT_01032013_inverse.nii.minf it changes the directory name but not the filename – p.deman Nov 29 '16 at 9:38
  • find /path/ -type f -name '0050ABC_01032013' -exec rename -n 's/0050ABC_01032013/0044CBA_01011901/' '{}' \; the paths are path of files, not directory, no problem with the find. it's the rename which here doesn't change the filename but changes the expression corresponding to the directory and not the expression in the filename – p.deman Nov 29 '16 at 9:48
  • @p.deman edited, sorry about that :) – Zanna Nov 29 '16 at 10:06
  • @p.deman that's great to hear :) – Zanna Nov 29 '16 at 10:26

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.