Skip to content

Instantly share code, notes, and snippets.

@hyamamoto
Last active August 29, 2015 14:13
Show Gist options
  • Save hyamamoto/d88b10742a5bab963cbb to your computer and use it in GitHub Desktop.
Save hyamamoto/d88b10742a5bab963cbb to your computer and use it in GitHub Desktop.
Sequentially Named File Generator. A bash shell script that creates a next 4-digit numbered file.
#!/bin/bash
# -------------------------------------------------------
# Sequentially Named File Generator.
#
# Create a new numbered file based on the given filename.
#
# Example:
#
# * "test.txt" -> "test####.txt"
# * "test" -> "test####"
# * ".txt" -> "####.txt"
# * "" -> "####"
# -------------------------------------------------------
shopt -s nullglob
num_pat="[0-9][0-9][0-9][0-9]"
file_prefix="${1%.*}"
[[ $1 = *.* ]] && file_ext="${1##*.}"
[ -n "$file_ext" ] && file_ext=.$file_ext
echo "[$0] prefix=\"$file_prefix\" suffix=\"$file_ext\""
echo "[$0] Checking \"${file_prefix}NNNN${file_ext}\" ..."
current_list=($file_prefix$num_pat$file_ext)
echo $current_list
if [ -z "$current_list" ]
then
echo "[$0] No matching file found."
num=0
else
last_file=${current_list[${#current_list[@]}-1]}
echo "[$0] \"$last_file\" found."
num="${last_file##$file_prefix}"
num="${num%*$file_ext}"
num=$((++num))
echo $num
fi
new_file_name=$(printf "%s%04d%s" "$file_prefix" "$num" "$file_ext")
echo "[$0] Creating \"$new_file_name\" ..."
touch "$new_file_name"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment