0

I'm trying to figure out how to rename multiple files (100s) that have different extensions to their respective sub directory name. Here is the structure:

Parentdir
  |--subdir1 
    |---name1.txt
    |---name2.jpeg
    |--name3.ovc
  |--subdir2
    |--name4.txt
    |--name5.tiff
    |-name6.mpeg

what I would like to do is batch process a rename of all files within their respective subdir name while maintaining their extension.

From the parent directory I was using this command but I'm having issues with the file extensions:

for subdir in *; do mv $subdir/*  $subdir.mpeg; done;
3
  • 2
    What is the "respective subdir"? Just the extension, like txt, jpeg, ovc, etc? In other words: what is the expected outcome?
    – PerlDuck
    Dec 28, 2018 at 19:35
  • 1
  • Your question is unclear. It would be helpful if you could add an example of old + new filename, or show example of new structure ( i.e. , edited example of what you have as structure in the question ) Dec 31, 2018 at 9:54

1 Answer 1

0

I conjured this script that can help to achieve what you want:

#!/usr/bin/env bash
set -e

for i in "$1"/*/*
do
    old="${i##*/}"
    ext="${i##*.}"
    name=$(basename "${i%/*}")
    [ ! -d "$i" ] && [ ! -f "$1/$name/$name.$ext" ] && mv "$1/$name/$old" "$1/$name/$name.$ext"

done

Test:

parentdir
├── subdir1
│   ├── name1.ovc
│   └── name1.txt
└── subdir2
    ├── name2.ovc
    └── name2.txt

Results:

parentdir
├── subdir1
│   ├── subdir1.ovc
│   └── subdir1.txt
└── subdir2
    ├── subdir2.ovc
    └── subdir2.txt

Usage: ./script.sh Parentdir

Information:

  • old="${i##*/}": returns filename to change (name1.ovc)
  • ext="${i##*.}": returns file extension (mpeg, txt)
  • name=$(basename "${i%/*}"): returns immediate parent directory of target file (subdir1)
  • [ ! -d "$i" ]: check if not a directory
  • [ ! -f "$1/$name/$name.$ext" ]: Check if the file already exists and has been renamed already
1
  • Hi George, thanks again and I have one more question. I ran the script and sometimes the file already has the same name as the directory it is in. I get a 'same name' message and the script stops. How can I modify to skip the file and move on to the next one? Jan 4, 2019 at 5:44

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.