spacereplace 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. #!/bin/bash
  2. # spacereplace v1.0.1 by Richard van Kampen - july 2005
  3. function helpme {
  4. echo ""
  5. echo "Help for spacereplace"
  6. echo ""
  7. echo "spacereplace version 1.0.1 - written by Richard van Kampen"
  8. echo "Tool to substitute spaces in file and directory names with underscores."
  9. echo ""
  10. echo "Usage: spacereplace [option] [PATH]"
  11. echo ""
  12. echo "List of options:"
  13. echo ""
  14. echo "-h or --help : show help."
  15. echo "-r : recursive. Also commit changes to all sub-directories."
  16. echo ""
  17. echo "You have to specify the path to the directory you want to process. Not specifying a path will just display help"
  18. echo ""
  19. echo "Example: 'spacereplace -r /home/richard/video' changes all spaces to underscores in /home/richard/mp3 and all directories below /home/richard/mp3."
  20. echo ""
  21. exit
  22. }
  23. for arg in "$@" # grab command line options
  24. do
  25. if [ "$arg" != "-r" ] && [ "$arg" != "-h" ]; then
  26. dir="$arg"
  27. orgdir="$dir"
  28. sub=" and sub-directories"
  29. fi
  30. case "$arg" in
  31. -h | --help ) help=1 ;; # help option true.
  32. -r ) recursive=1 ;; # recursive is true
  33. esac
  34. done
  35. if [ "$dir" == "" ];then
  36. helpme
  37. fi
  38. if [ ! -d "$dir" ]; then
  39. echo "Directory $dir does not exist. Please try again with full path"
  40. exit
  41. fi
  42. if [ "$help" = "1" ]; then # do this if -h option is used
  43. helpme
  44. fi
  45. function delspaces {
  46. strips=1;
  47. teller=1; # iterate through 'contentgrab' array
  48. cd $dir;
  49. # rename @ because we need it. Do it 5 times
  50. until [ $strips = "5" ];do
  51. rename @ - *
  52. let strips+=1
  53. done
  54. for i in $(ls | sed 's/\n//g' | sed 's/\ /@/g'); do
  55. i=${i//@/ }
  56. contentgrab[$teller]=$i
  57. replacespace=${contentgrab[$teller]// /_}
  58. if [ "${contentgrab[$teller]}" != "$replacespace" ] && [ ! -f "$replacespace" ] && [ ! -d "$replacespace" ]; then
  59. mv -- "${contentgrab[$teller]}" "$replacespace"
  60. fi
  61. let teller+=1;
  62. done
  63. }
  64. teller3=1;
  65. function getdirs {
  66. for i in $(echo */); do
  67. if [ "$i" != "*/" ];then
  68. j[$teller3]=${i%/}
  69. contentdirs[$teller3]=$dir/${j[$teller3]}
  70. let teller3+=1
  71. fi
  72. done
  73. }
  74. delspaces
  75. getdirs
  76. counter4=1
  77. if [ "$recursive" = "1" ]; then
  78. until [ "${contentdirs[$counter4]}" == "" ]; do
  79. dir=${contentdirs[$counter4]}
  80. let counter4+=1
  81. delspaces
  82. getdirs
  83. done
  84. orgdir="$orgdir$sub"
  85. fi
  86. echo ""
  87. echo "Changed all spaces to underscores in $orgdir"