Advertisement
Guest User

Untitled

a guest
May 28th, 2022
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.04 KB | None | 0 0
  1. #!/bin/bash
  2.  
  3. get_help=false
  4. recursive=false
  5.  
  6. function get_args(){
  7. # get arguments
  8. for var in "$@"
  9. do
  10. case $var in
  11. -h|-help) get_help=true;;
  12. -r|-recursive) recursive=true;;
  13. *) search_dir=$var
  14. esac
  15. done
  16. }
  17.  
  18. function print_help_text(){
  19. # print help text and exit
  20. echo "format filenames in a directory, perhaps recursively"
  21. echo "usage: format_directory [options] PATH"
  22. echo " -h | -help print this help text and exit"
  23. echo " -r | -recursive format files recursively"
  24. exit
  25. }
  26.  
  27. # if user hasn't passed any arguments, print help text and exit
  28. if [ $# -eq 0 ]; then
  29. echo "error--you haven't passed any arguments"
  30. print_help_text
  31. exit 1
  32. fi
  33.  
  34. get_args "$@"
  35.  
  36. # if passed help flag, print help text and exit
  37. if $get_help
  38. then
  39. print_help_text
  40. fi
  41.  
  42. # write find command
  43. find_command="find "$search_dir
  44. if $recursive
  45. then
  46. echo "formatting files recursively"$'\n'
  47. else
  48. echo "only formatting paths in directory you've specified"$'\n'
  49. find_command="$find_command"" -maxdepth 1"
  50. fi
  51. echo "find command:"$'\n'"${find_command}"$'\n'$'\n'"formatted paths:"$'\n'
  52.  
  53. # run find command and loop through results
  54. $find_command | while read line; do
  55.  
  56. # get directory and filename
  57. directory=$(dirname "${line}");
  58. filename=$(basename "${line}");
  59.  
  60. # skip hidden files with folder info
  61. if [ "$filename" != '.DS_Store' ] && [ "$filename" != 'desktop.ini' ]
  62. then
  63.  
  64. # make filename lowercase
  65. filename=$(echo "$filename" | tr '[A-Z]' '[a-z]')
  66.  
  67. # for files, replace spaces and dashes with underscores
  68. if [ -f "${line}" ]
  69. then
  70. filename=$(echo "${filename}" | tr ' ' _)
  71. filename=$(echo "${filename}" | tr - _)
  72.  
  73. # for directories, replace spaces and underscores with dashes
  74. elif [ -d "${line}" ]
  75. then
  76. filename=$(echo "${filename}" | tr ' ' -)
  77. filename=$(echo "${filename}" | tr _ -)
  78.  
  79. fi
  80.  
  81. # get new name, print old and new paths, move file
  82. new_path="$directory"/"$filename"
  83. echo "old path: ""${line}"
  84. echo "new path: ""${new_path}"
  85.  
  86. move_command='mv ''"'"$line"'" "'"$new_path"'"'
  87. echo $move_command
  88. "$move_command"
  89. echo ""
  90.  
  91. fi
  92. done
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement