1

I got help regarding the following question: batch rename files with ids intact

It's a great example of how to rename specific files in a group, but I am wondering if there is a similar script I could use to do the following:

  1. I have a group of nested folders and files within a root directory that contain [myprefix_foldername] and [myprefix_filename.ext]
  2. I would like to rename all of the folders and files to [foldername] and [filename.ext]

Can I use a similar methodology to what is found in the post above?

Thanks! jml

Community
  • 1
  • 1
jml
  • 1,745
  • 6
  • 29
  • 55

1 Answers1

1

Yes, quite easily, with find.

find rootDir -name "myprefix_*"

This will give you a list of all files and folders in rootDir that start with myprefix_. From there, it's a short jump to a batch rename:

find rootDir -name "myprefix_*" | while read f
do
  echo "Moving $f to ${f/myprefix_/}"
  mv "$f" "${f/myprefix_/}"
done

EDIT: IFS added per http://www.cyberciti.biz/tips/handling-filenames-with-spaces-in-bash.html

EDIT 2: IFS removed in favor of while read.

EDIT 3: As bos points out, you may need to change while read f to while read -d $'\n' f if your version of Bash still doesn't like it.

Chriszuma
  • 4,464
  • 22
  • 19
  • what if there are spaces in the folder names? it seems to fail under those circumstances... let me know if you need more specifics. – jml Oct 27 '11 at 19:51
  • I can't see why it would fail. Did you remember to put the quotes around `$f` and `${f/myprefix_/}`? Let me see how it is failing. – Chriszuma Oct 27 '11 at 20:21
  • the echo fails... i wanted to check it with that first. – jml Oct 27 '11 at 20:25
  • Did you copy it directly from my answer? It seems to be working fine for me. What is the exact filename it fails on? – Chriszuma Oct 27 '11 at 20:27
  • it's a folder- i have a folder named 'myprefix_foldername Project', and it reads out 'Moving Project to Project' – jml Oct 27 '11 at 20:30
  • 1
    Oooooooohhhhhhhhhhhhhh........ Okay yeah, the `for` command is splitting up the space-laden filenames. Easiest solution I could find it to put `IFS="\n"` in your script, as seen here: http://www.linuxquestions.org/questions/programming-9/bash-scripting-add-a-character-to-a-line-134724/#post700774 – Chriszuma Oct 27 '11 at 20:48
  • 1
    @jml - I came up with a slightly less messy way that doesn't require `IFS`. See edited answer. – Chriszuma Oct 27 '11 at 20:59
  • 1
    What we don't know here is the version of jml's bash. Older bashes has SPACE as delimiter for "read", while newer have \n. If jml uses an old version, change `while read f` into `while read -d '\n' f`. – bos Oct 27 '11 at 22:35
  • @Chriszuma - thanks a million. also; i'm on osx 10.7; i think that the bash shell should be just fine for usage of 'while'. – jml Oct 28 '11 at 01:56