fixname (1967B)
1 #!/usr/bin/env bash 2 3 # Description: Clean filename or dirname (either hovered or selections) 4 # to be more shell-friendly. This script cleans 5 # non A-Za-z0-9._- characters. 6 # and replaces it with underscore (_). 7 # 8 # It supports cleaning single/double quote, newline, 9 # leading, trailing spaces. 10 # 11 # eg. 12 # to be continued (つづく).mp4 -> to_be_continued______.mp4 13 # [work] stuff.txt -> _work__stuff.txt 14 # home's server -> home_s_server 15 # qwe\trty -> __qwe_rty 16 # 17 # And if there are two almost similar filenames 18 # like: 'asd]f' and 'asd f' both will be renamed to 'asd_f', 19 # to avoid overwriting, the last file will be prepended by _. 20 # So they will be: 'asd_f' and '_asd_f' 21 # 22 # Dependencies: sed 23 # 24 # Shell: Bash 25 # Author: Benawi Adha 26 27 prompt=true 28 sel=${NNN_SEL:-${XDG_CONFIG_HOME:-$HOME/.config}/nnn/.selection} 29 30 cleanup() { 31 # printf "%s" "$1" | sed -e 's/[^A-Za-z0-9._-]/_/g' 32 printf "%s" "$1" | sed 's/[^A-Za-z0-9._-]/_/g' | sed ':a;N;$!ba;s/\n/_/g' 33 } 34 35 if [ -s "$sel" ]; then 36 targets=() 37 while IFS= read -r -d '' i || [ -n "$i" ]; do 38 targets+=( "$(basename "$i")" ) 39 done < "$sel" 40 else 41 targets=("$1") 42 fi 43 44 for i in "${targets[@]}"; do 45 printf "%s -> %s\n" "$i" "$(cleanup "$i")"; 46 done 47 48 if $prompt; then 49 echo 50 printf "Proceed [Yn]? " 51 read -r input 52 case "$input" in 53 y|Y|'') 54 ;; 55 *) 56 echo "Canceled" 57 exit 58 ;; 59 esac 60 fi 61 62 for i in "${targets[@]}"; do 63 if [ "$i" != "$(cleanup "$i")" ]; then 64 tmp='' 65 if [ -e "$(cleanup "$i")" ]; then 66 tmp='_' 67 fi 68 mv "$i" "$tmp$(cleanup "$i")"; 69 fi 70 done 71 72 # Clear selection 73 if [ -s "$sel" ] && [ -p "$NNN_PIPE" ]; then 74 printf "-" > "$NNN_PIPE" 75 fi