Bash Script to prefix files with sequential numbers in a directory

If you have a use case where you want to prefix files within a directory with number sequences such as 001, 002, 003 .... 999. Well, for such a case you can simply write a bash script that can do this job quickly.

Below is a very simple script in bash that will do this job for you, just keep the file in the folder where you want to run it. For safety, it will ask you to enter the list of file extensions that you want to rename with a number prefix, you can add any number of file extensions separated by space. example "csv xml xls xlsx json txt"


# Script to add a numeric prefix to files within a directory 
# Author:
# Date Created: 4/5/2023
# Note: User needs to provide the file extensions eg. txt, CSV, xlsx
# to consider only those types.
# DISCLAIMER: Use this script at your own risk. 
# We are not responsible for any damage it may cause.

echo "Enter the file extensions you want to rename (separated by spaces):"
read -ra extensions


for ext in "${extensions[@]}"; do
    for file in *."$ext"; do
        new_name="$(printf "%03d" $file_count)-$file"
        mv "$file" "$new_name"
# ./

Enter the file extensions you want to rename (separated by spaces):
csv txt

# ls -l
total 8
-rw-r--r--  1 c2ctech  staff    0 May  4 23:09 001-file-c.csv
-rw-r--r--  1 c2ctech  staff    0 May  4 23:09 002-file-d.csv
-rw-r--r--  1 c2ctech  staff    0 May  4 23:09 003-file-a.txt
-rw-r--r--  1 c2ctech  staff    0 May  4 23:09 004-file-b.txt
-rwxr-xr-x@ 1 c2ctech  staff  669 May  4 23:02

prefix files with number sequence bash script example

You may customize the script if you have files over 999 and if you want to have a custom string prefixed as well or use the underscore operator instead of a hyphen.


Have Questions? Post them here!