You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

59 lines
1.7 KiB

#!/bin/bash
# Replaces odd characters in filenames and directories with an underline
# When there are more consecutive odd characters what would result in ____ sth like this, it collates to a single underline.
# When the new unixified filename is already taken, a counted suffix will be added before an eventuel period in the filename, otherwise just append.
# Will never overwrite a file.
# usage: inixify.sh [filename]
# filename The file to unixify, can be file or folder.
export IFS=$'\n'
export fname_full=$1
#export out=$2;
function sanitise {
local retval=$(echo $1 | gsed -e 's/[^A-Za-z0-9#./_-]/_/g') # replace everything else with _
retval=$(echo $retval | gsed -e 's/\.\{2,\}/\./g') # replace >1 consecutive . with one .
retval=$(echo $retval | gsed -e 's/_\{2,\}/_/g') # replace >1 consecutive _ with one _
echo $retval
}
export current_dir=$(dirname $fname_full)
export current_file=$(basename $fname_full)
export fname_new=$(sanitise $current_file) # unixify
if [ "$current_file" != "$fname_new" ]; then { #any changes been needed?
count=1
while [ -e $current_dir/$fname_new ]; do { #new filename already taken?
#echo file exists: $current_dir/$fname_new;
#add suffix before any dot, if no dot just append
if [[ "$fname_new" =~ \. ]]; then {
fname_new=$(echo $fname_new | sed -e "s/\./_$count\./g")
}; else {
fname_new=$fname_new"_$count"
}; fi
count=$(($count + 1))
}; done
echo -n $current_dir/$fname_new
if [ "$count" -gt 1 ]; then {
echo " suffix nr added: $(($count - 1))"
}; else {
echo ""
}; fi
export cmd="mv \"$fname_full\" \"$current_dir/$fname_new\""
# echo $cmd;
eval $cmd
}; else {
echo -ne
echo $fname_full" filename already ok."
}; fi