I have been attempting to rename a bunch of files to their directories.

I have multiple directories with spaces and no spaces /The Dark Tower.

In it are multiple titles with file names with spaces and no spaces as well:

/The Dark Tower/TDT feature.mov
/The Dark Tower/Main Trailer.mov 
/The Dark Tower/Trailer_Sub

I need to change the files in these directories with the name of the folder adding a number to the end of the file name:

/The Dark Tower/TDT feature.mov   ->   /The Dark Tower/The Dark Tower1.mov

/The Dark Tower/Main Trailer.mov  ->   /The Dark Tower/The Dark Tower2.mov

/The Dark Tower/Trailer_Sub       ->   /The Dark Tower/The Dark Tower3.mov

I have been doing this manually, but I would rather be able to do this with one script for 100 of movie titles I have. I know it can be done, but my current attempts have not been successful.

  • Do you need the file to be ordered? – cuonglm Mar 4 '16 at 2:51
  • @cuonglm No, I just need unique file names. I wanted to name them to the directory, but since a directory could contain multiple files, I need a way to make the title different since the file type is the same. – Austin Perez Mar 4 '16 at 2:55
  • Any directories/titles with more than 9 files in them? – Jeff Schaller Mar 4 '16 at 2:55
  • @JeffSchaller No, no more than 5 – Austin Perez Mar 4 '16 at 2:56

Renaming Files with Bashisms

There are certainly other ways to do this, but if you're looking for a pure Bash solution that doesn't rely on any utilities other than the shell itself, the following will work.

dir="The Dark Tower"
declare -i count=1
for file in "$dir"/*.mov; do
    mv "$file" "${dir}/${dir} ${count}.mov"
| improve this answer | |
  • The Dark Tower is just one of the Directories of Several. It is a child of the current Parent directory I am in. There are multiple child directories in here. How can I do this with all of the directories from the parent? – Austin Perez Mar 4 '16 at 3:15
  • 1
    @AustinPerez Instead of assigning dir as a fixed string, you can wrap the rest of the rename code in another loop like for dir in *, or a specific list of quoted subdirectories instead of a glob. You are only limited by your glob-fu and your imagination. – CodeGnome Mar 4 '16 at 4:52

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.