DylanDog
DylanDog

Reputation: 109

Bash SH Script - Rename File with specific extension + Move to specific location

SEE VISUAL EXPLANATION and EDIT

I'm trying to create a bash script to do a rename+move.

This is the example situation:

         |DOCTEMP - NameOfTheFolder---------|NameOfADocument.docx
FOLDER---|
         |DOCFINAL - OtherNameOfTheFolder---|OtherNameOfADocument.pdf
         |
         |etc.

What I want to do is a script that:

Part I

Only if the file has docx, pdf, ppt then rename it as its folder but without DOCTEMP - / DOCFINAL -.

NameOfADocument.docx => NameOfTheFolder.docx

OtherNameOfADocument.pdf => OtherNameOfTheFolder.pdf

Part II

After renaming, move that file to another folder depending on the first part of the name of the old folder.

NameOfTheFolder.docx => if **DOCTEMP** then => /ROOT/DOCTEMP/NameOfTheFolder.docx

OtherNameOfTheFolder.docx => if **DOCFINAL** then => /ROOT/DOCFINAL/OtherNameOfTheFolder.pdf

I tried using something like this but it doesn't work

#!/bin/bash

cd "$ROOT/FOLDER"
# for filename in *; do
find . -type f | while IFS= read filename; do # Look for files in all ~/FOLDER sub-dirs
  case "${filename,,*}" in  # this syntax emits the value in lowercase: ${var,,*}  (bash version 4)
     *.part) : ;; # Excludes *.part files from being moved
     move.sh) : ;;
     *test*)            mv "$filename" "$ROOT/DOCTEMP/" ;; # Using move there is no need to {&& rm "$filename"}
     *) echo "Don't know where to put $filename" ;;
  esac
done

EDIT: Visual explanation

given

ROOT/DOWNLOADS/OFFICE - House/file.docx
              /IWORK - Car/otherfile.docx

then Part I

ROOT/DOWNLOADS/OFFICE - House/House.docx
              /IWORK - Car/Car.docx

then Part II

ROOT/DOCUMENTS/OFFICE/House.docx
              /IWORK/Car.docx

docx can be pdf or ppt; here only an example

EDIT2: Final script

 #!/bin/bash
shopt -s nullglob
for filename in /ROOT/DOWNLOADS/{OFFICE,IWORK}/*/*.{docx,pdf,ppt}; do
    new_path="$(dirname $filename).${filename##*.}"
    new_path="${new_path/DOWNLOADS/DOCUMENTS}"
    echo "moving $filename -> $new_path"
    mv "$filename" "$new_path" 
done

Upvotes: 0

Views: 793

Answers (1)

Håken Lid
Håken Lid

Reputation: 23064

I might have missed some points in that explanation. But would this do what you want?

#!/bin/bash
shopt -s nullglob
for filename in /ROOT/DOWNLOADS/{OFFICE,IWORK}/*/*.{docx,pdf,ppt}; do
    new_path="$(dirname $filename).${filename##*.}"
    new_path="${new_path/DOWNLOADS/DOCUMENTS}"
    echo "moving $filename -> $new_path"
    mv "$filename" "$new_path" 
done

Upvotes: 1

Related Questions