Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/bin/bash
- get_help=false
- recursive=false
- function get_args(){
- # get arguments
- for var in "$@"
- do
- case $var in
- -h|-help) get_help=true;;
- -r|-recursive) recursive=true;;
- *) search_dir=$var
- esac
- done
- }
- function print_help_text(){
- # print help text and exit
- echo "format filenames in a directory, perhaps recursively"
- echo "usage: format_directory [options] PATH"
- echo " -h | -help print this help text and exit"
- echo " -r | -recursive format files recursively"
- exit
- }
- # if user hasn't passed any arguments, print help text and exit
- if [ $# -eq 0 ]; then
- echo "error--you haven't passed any arguments"
- print_help_text
- exit 1
- fi
- get_args "$@"
- # if passed help flag, print help text and exit
- if $get_help
- then
- print_help_text
- fi
- # write find command
- find_command="find "$search_dir
- if $recursive
- then
- echo "formatting files recursively"$'\n'
- else
- echo "only formatting paths in directory you've specified"$'\n'
- find_command="$find_command"" -maxdepth 1"
- fi
- echo "find command:"$'\n'"${find_command}"$'\n'$'\n'"formatted paths:"$'\n'
- # run find command and loop through results
- $find_command | while read line; do
- # get directory and filename
- directory=$(dirname "${line}");
- filename=$(basename "${line}");
- # skip hidden files with folder info
- if [ "$filename" != '.DS_Store' ] && [ "$filename" != 'desktop.ini' ]
- then
- # make filename lowercase
- filename=$(echo "$filename" | tr '[A-Z]' '[a-z]')
- # for files, replace spaces and dashes with underscores
- if [ -f "${line}" ]
- then
- filename=$(echo "${filename}" | tr ' ' _)
- filename=$(echo "${filename}" | tr - _)
- # for directories, replace spaces and underscores with dashes
- elif [ -d "${line}" ]
- then
- filename=$(echo "${filename}" | tr ' ' -)
- filename=$(echo "${filename}" | tr _ -)
- fi
- # get new name, print old and new paths, move file
- new_path="$directory"/"$filename"
- echo "old path: ""${line}"
- echo "new path: ""${new_path}"
- move_command='mv ''"'"$line"'" "'"$new_path"'"'
- echo $move_command
- "$move_command"
- echo ""
- fi
- done
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement