Move file according to specific pattern in filename while retaining the folder structure

Viewed 111

i need to move all the files having the string "Unknown Quality" in their filename along with its outer 2 folders to a folder named as "Unknown" which is present in the same directory as the base folder. i would like to add that in the base folder , the files are 3 folders deep , so while moving the matched files it should leave the $folder1 in base_folder itself.

Unknown_folder

base_folder
  $folder1
    $folder2
      $folder3
        $filename-Unknown Quality.mpk/mp4/avi

################### Expected result ###################

Unknown_folder
  $folder2
    $folder3
      $filename-Unknown Quality.mpk/mp4/avi

base_folder
  $folder1

After some searching , i came accross this basic find command athough its not suitable for me as it simply moves the files matching the pattern and ingores directory structure . As i have explained above while moving the matched files , i need the outer 2 directory structure relative to the matched file moved as well

find . -name "*Unknown Quality*" -exec mv "{}" Unknown \;   

Hopefully someone can help me out . I am not very sure whats the best approach but bash , perl , python all of these should acheive this very easily

1 Answers

Would you please try the following:

#!/bin/bash

find root -name "*Unknown Quality*" -type f -print0 | while IFS= read -r -d "" f; do
    f2=${f%/*}          # removes the rightmost "/" and following filename
    f2=${f2%/*}         # removes the second rightmost "/" and following dirname
    if [[ -d $f2 ]]; then
                        # consider the case the folder is already removed
        mv -- "$f2" "Unknown_folder"
    fi
done

Please note that the code above does not consider the case the same dirname conflicts in the directory "Unknown_folder".

Related