2021-03-27 14:06:17 +00:00
|
|
|
#!/usr/bin/env bash
|
2021-03-24 09:21:38 +00:00
|
|
|
|
2021-03-25 19:36:25 +00:00
|
|
|
# Description: Clean filename or dirname (either hovered or selections)
|
2021-03-27 14:06:17 +00:00
|
|
|
# to be more shell-friendly. This script cleans
|
2021-05-14 12:03:28 +00:00
|
|
|
# non A-Za-z0-9._- characters.
|
2021-03-27 14:06:17 +00:00
|
|
|
# and replaces it with underscore (_).
|
2021-03-24 09:21:38 +00:00
|
|
|
#
|
2021-03-27 14:06:17 +00:00
|
|
|
# It supports cleaning single/double quote, newline,
|
|
|
|
# leading, trailing spaces.
|
|
|
|
#
|
|
|
|
# eg.
|
|
|
|
# to be continued (つづく).mp4 -> to_be_continued______.mp4
|
|
|
|
# [work] stuff.txt -> _work__stuff.txt
|
|
|
|
# home's server -> home_s_server
|
|
|
|
# qwe\trty -> __qwe_rty
|
|
|
|
#
|
|
|
|
# And if there are two almost similar filenames
|
2021-05-14 12:03:28 +00:00
|
|
|
# like: 'asd]f' and 'asd f' both will be renamed to 'asd_f',
|
2021-03-27 14:06:17 +00:00
|
|
|
# to avoid overwriting, the last file will be prepended by _.
|
|
|
|
# So they will be: 'asd_f' and '_asd_f'
|
2021-03-24 09:21:38 +00:00
|
|
|
#
|
|
|
|
# Dependencies: sed
|
|
|
|
#
|
2021-03-27 14:06:17 +00:00
|
|
|
# Shell: Bash
|
2021-03-24 09:21:38 +00:00
|
|
|
# Author: Benawi Adha
|
|
|
|
|
|
|
|
prompt=true
|
|
|
|
sel=${NNN_SEL:-${XDG_CONFIG_HOME:-$HOME/.config}/nnn/.selection}
|
|
|
|
|
|
|
|
cleanup() {
|
2021-03-27 14:06:17 +00:00
|
|
|
# printf "%s" "$1" | sed -e 's/[^A-Za-z0-9._-]/_/g'
|
|
|
|
printf "%s" "$1" | sed 's/[^A-Za-z0-9._-]/_/g' | sed ':a;N;$!ba;s/\n/_/g'
|
2021-03-24 09:21:38 +00:00
|
|
|
}
|
|
|
|
|
2021-03-27 11:37:58 +00:00
|
|
|
if [ -s "$sel" ]; then
|
2021-03-27 14:06:17 +00:00
|
|
|
targets=()
|
|
|
|
while IFS= read -r -d '' i || [ -n "$i" ]; do
|
|
|
|
targets+=( "$(basename "$i")" )
|
|
|
|
done < "$sel"
|
2021-03-24 09:21:38 +00:00
|
|
|
else
|
2021-03-27 14:06:17 +00:00
|
|
|
targets=("$1")
|
2021-03-24 09:21:38 +00:00
|
|
|
fi
|
|
|
|
|
2021-03-27 14:06:17 +00:00
|
|
|
for i in "${targets[@]}"; do
|
|
|
|
printf "%s -> %s\n" "$i" "$(cleanup "$i")";
|
2021-03-24 09:21:38 +00:00
|
|
|
done
|
|
|
|
|
|
|
|
if $prompt; then
|
|
|
|
echo
|
|
|
|
printf "Proceed [Yn]? "
|
|
|
|
read -r input
|
|
|
|
case "$input" in
|
|
|
|
y|Y|'')
|
|
|
|
;;
|
|
|
|
*)
|
|
|
|
echo "Canceled"
|
|
|
|
exit
|
|
|
|
;;
|
|
|
|
esac
|
|
|
|
fi
|
|
|
|
|
2021-03-27 14:06:17 +00:00
|
|
|
for i in "${targets[@]}"; do
|
2021-03-24 09:21:38 +00:00
|
|
|
if [ "$i" != "$(cleanup "$i")" ]; then
|
2021-03-25 19:36:25 +00:00
|
|
|
tmp=''
|
|
|
|
if [ -e "$(cleanup "$i")" ]; then
|
|
|
|
tmp='_'
|
|
|
|
fi
|
|
|
|
mv "$i" "$tmp$(cleanup "$i")";
|
2021-03-24 09:21:38 +00:00
|
|
|
fi
|
|
|
|
done
|
2021-03-27 11:37:58 +00:00
|
|
|
|
|
|
|
# Clear selection
|
|
|
|
if [ -s "$sel" ] && [ -p "$NNN_PIPE" ]; then
|
|
|
|
printf "-" > "$NNN_PIPE"
|
|
|
|
fi
|