Advertisement
freddy87

Bash for batch renaming V2

Jun 12th, 2016
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.19 KB | None | 0 0
  1. #!/bin/bash
  2.  
  3. #Script moulded by freddy87
  4. #Version 2
  5.  
  6.  
  7. read -p "Enter the filetype you want to rename: ." extension #option to select filename extension
  8. read -p "Enter a prefix for the renamed files: " prefix #option to put a prefix eg. Birthday_
  9. file_num=$(ls -1 *.$extension| grep -v '/$' | wc -l) #counts files in folder of type $extension
  10. echo "Number of files to rename: "$file_num #output for peace of mind
  11. padding=${#file_num} #gets length of file_num for padding to give each filename
  12. echo "Length of padding in filename: "$padding #output for peace of mind
  13.  
  14. if [ "$extension" = "JPG" ]; then
  15. for f in *.$extension; do
  16. mv "$f" "${f%.JPG}.jpg"
  17. done
  18. echo "*.JPG renamed to *.jpg"
  19. a=1
  20. for i in *.$extension; do
  21. if [ -n "$prefix" ]; then
  22. new=$(printf $prefix"_%0"$padding"d."$extension "$a") #$padding appropriate to number of files
  23. if [ "$prefix""_""$new" = "$i" ]; then
  24. echo "Error: Filenames matching already"
  25. elif [ "$new" != "$i" ]; then
  26. mv -- "$i" "$new" #renames files
  27. let a=a+1
  28. fi
  29. elif [ -z "$prefix" ]; then
  30. new=$(printf "%0"$padding"d."$extension "$a") #$padding appropriate to number of files
  31. if [ "$new" = "$i" ]; then
  32. echo "Error: Filenames matching already"
  33. elif [ "$new" != "$i" ]; then
  34. mv -- "$i" "$new" #renames files
  35. let a=a+1
  36. fi
  37. fi
  38. done
  39. elif [ "$extension" != "JPG" ]; then
  40. a=1
  41. for i in *.$extension; do
  42. if [ -n "$prefix" ]; then
  43. new=$(printf $prefix"_%0"$padding"d."$extension "$a") #$padding appropriate to number of files
  44. if [ "$prefix""_""$new" = "$i" ]; then
  45. echo "Error: Filenames matching already"
  46. elif [ "$new" != "$i" ]; then
  47. mv -- "$i" "$new" #renames files
  48. let a=a+1
  49. fi
  50. elif [ -z "$prefix" ]; then
  51. new=$(printf "%0"$padding"d."$extension "$a") #$padding appropriate to number of files
  52. if [ "$new" = "$i" ]; then
  53. echo "Error: Filenames matching already"
  54. elif [ "$new" != "$i" ]; then
  55. mv -- "$i" "$new" #renames files
  56. let a=a+1
  57. fi
  58. fi
  59. done
  60. fi
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement