Skip to content

Instantly share code, notes, and snippets.

@caramelchocolate
Last active February 8, 2019 02:38
Show Gist options
  • Save caramelchocolate/c4fd304772da03d31bb296e37eb8f918 to your computer and use it in GitHub Desktop.
Save caramelchocolate/c4fd304772da03d31bb296e37eb8f918 to your computer and use it in GitHub Desktop.
Numbering files
#!/bin/sh
prefix="__"
usage_error ()
{
echo "$0: $*" >&2
print_usage >&2
exit 2
}
print_usage ()
{
cat <<END
Usage:
numbering_files.sh [--prefix=PREFIX] PATH
END
}
while test $# -gt 0; do
case $1 in
--prefix) prefix=$2; shift;;
--) shift; break;;
-*) usage_error "invalid option: '$1'";;
*) break;;
esac
shift
done
target_path=${1:-$(pwd)}
find ${target_path} ! -name '*.DS_Store' -type f -mindepth 1 |\
# natural sort order
sort -Vk1,1 |\
# Use \0(Null character) as the field delimiter.
# FS is not space.
awk -v FS='\36' '{printf("%s%c",$1,0);}' |\
# $f -> filename
# $d -> directory name
# $e -> extension
# \36(oct) -> Record Separator(RS)
xargs -0 -L1 -I@ sh -c 'f="@";d=$(dirname "${f}");e=${f##*.}; printf "%s\36%s\36%s\n" "${f}" "${d}" "${e}"' |\
# \47(oct) -> '
awk -v PREFIX=${prefix} -F$'\36' '{c=sprintf("mv -nv \47%s\47 \47%s/%s%s.%s\47",$1,$2,PREFIX,NR,$3);system(c)close(c);}'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment