Advertisement
Guest User

Untitled

a guest
Oct 22nd, 2019
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.02 KB | None | 0 0
  1. #!/usr/bin/env zsh -f
  2. # Purpose: use 'file' command to make sure image files have proper extension
  3. #
  4. # From: Timothy J. Luoma
  5. # Mail: luomat at gmail dot com
  6. # Date: 2019-10-04
  7.  
  8. NAME="$0:t:r"
  9.  
  10. if [[ -e "$HOME/.path" ]]
  11. then
  12. source "$HOME/.path"
  13. else
  14. PATH='/usr/local/scripts:/usr/local/bin:/usr/bin:/usr/sbin:/sbin:/bin'
  15. fi
  16.  
  17. for i in "$@"
  18. do
  19.  
  20. if [[ -f "$i" ]]
  21. then
  22.  
  23. # make sure we have the full path to '$i'
  24. i=($i(:A))
  25.  
  26. TYPE=$(file -b "$i" | awk '{print $1}')
  27.  
  28. case "$TYPE" in
  29. JPEG)
  30. # make it lowercase
  31. EXPECTED_EXT='jpg'
  32. ;;
  33.  
  34. PNG)
  35. # make it lowercase
  36. EXPECTED_EXT='png'
  37. ;;
  38.  
  39. ## If you want to add more filetypes, use `file -b "YourFileHere.ext" | awk '{print $1}'`
  40. ## and see what you get as output. Then replace 'FOO' with it and 'foo' with the
  41. ## proper extension.
  42. #
  43. # FOO)
  44. # # make it lowercase
  45. # EXPECTED_EXT='foo'
  46. # ;;
  47.  
  48. *)
  49. echo "$NAME: '$i' is type '$TYPE' but I don't know what to do with that."
  50. continue
  51. ;;
  52. esac
  53.  
  54. ACTUAL_EXT="$i:e:l"
  55.  
  56. if [[ "$EXPECTED_EXT" == "$ACTUAL_EXT" ]]
  57. then
  58. # the EXT that the file has is what it should have
  59. echo " $NAME: '$i' has the proper extension."
  60.  
  61. continue
  62. fi
  63.  
  64. ## if we get here, then the extension does not match what we
  65. ## expected, which either means that it is a) missing or b) wrong
  66.  
  67. if [[ "$ACTUAL_EXT" == "" ]]
  68. then
  69. ## there is no extension, so we need to add one
  70.  
  71. NEWNAME="$i.$EXPECTED_EXT"
  72. else
  73. ## if we get here, the file has an extension
  74. ## but it is not the correct one
  75. NEWNAME="$i:r.$EXPECTED_EXT"
  76. fi
  77.  
  78. # initialize a counter
  79. COUNT='0'
  80.  
  81. while [[ -e "$NEWNAME" ]]
  82. do
  83. # if there is another file with the same name we want to use
  84. # add a digit to the filename
  85. # so 'foo.jpg' would become 'foo.1.jpg'
  86. # this loop will repeat if 'foo.1.jpg' also exists
  87.  
  88. ((COUNT++))
  89.  
  90. NEWNAME="$i:r.$COUNT.$EXPECTED_EXT"
  91.  
  92. done
  93.  
  94. # Once we get here we should be ready to rename the file
  95. # but we use `-n` just to be safe
  96.  
  97. mv -vn "$i" "$NEWNAME"
  98.  
  99. fi
  100.  
  101. done
  102.  
  103. exit 0
  104. #EOF
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement