Yunga

curatio.sh

Mar 2nd, 2015
344
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 1.68 KB | None | 0 0
  1. #!/bin/bash
  2. # See http://www.reddit.com/r/bash/comments/2xh32d/how_can_i_make_this_bash_script_better/
  3. dirs=("16x10" "16x9" "5x4" "4x3");
  4.  
  5. # Fills in known ratios -> dirs in an associative array
  6. declare -A ratios;
  7. for r in "${dirs[@]}"; do
  8.     ratios[$(echo $r | tr "x" "/" | bc -ql)]="$r"; # 1.77777... = 16x9
  9. done;
  10.  
  11. mkdir -p "${dirs[@]}" "Others"; # Creates directories
  12.  
  13. shopt -s nocaseglob # Case insensitive glob
  14. for file in *.{jpg,jpeg,gif,bmp,png}; do
  15.     if [[ -f "$file" ]]; then # Check if file exists (prevents *.xxx in $file)
  16.         # Current image ratio
  17.         curRatio=$(identify -format "%w/%h" "$file" -quiet | bc -ql 2>&1);
  18.  
  19.         if [[ ! -z "$curRatio" ]] ; then
  20.             # Move the file in the appropriate dir.
  21.             if [ ${ratios[$curRatio]+_} ]; then  # Check if ratio exists
  22.                 mv "$file" "${ratios[$curRatio]}";
  23.             else
  24.                 mv "$file" "Others/$file";
  25.             fi;
  26.         else
  27.             echo "Got a problem with $file.";
  28.         fi;
  29.     fi;
  30. done;
  31.  
  32. find "${dirs[@]}" "Others" -type d -empty -delete # Delete empty dirs
  33.  
  34. exit;
  35.  
  36. # ----------------------------------------------------------------------------
  37. # https://www.reddit.com/r/bash/comments/2xh32d/how_can_i_make_this_bash_script_better/cp0ofc8 (iscfrc)
  38.  
  39. mkdir -p 16x10 16x9 5x4 4x3 Others
  40.  
  41. declare -A ratio_map=([160]=16x10 [177]=16x9 [125]=5x4 [133]=4x3)
  42.  
  43. find . -maxdepth 1 -type f -iregex '.*\.\(jpe?g\|gif\|png\|bmp\)$' -printf '%f\t' -exec identify -format '%[fx:(w/h)*100]' '{}' \; |
  44. while IFS=$'\t' read -r file ratio; do
  45.         [[ "${ratio_map[${ratio%%.*}]}" ]] && outdir=${ratio_map[${ratio%%.*}]} || outdir=Others
  46.         mv -v "$file" $outdir
  47. done
  48.  
  49. find . -maxdepth 1 -type d -regex '.*/\([0-9]+x[0-9]+\|Others\)$' -empty -print -delete
Add Comment
Please, Sign In to add comment