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"

#!/bin/bash

# Script to add a numeric prefix to files within a directory 
#
# Author: Code2care.org
# 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

file_count=1

for ext in "${extensions[@]}"; do
    for file in *."$ext"; do
        extension="${file##*.}"
        new_name="$(printf "%03d" $file_count)-$file"
        mv "$file" "$new_name"
        ((file_count++))
    done
done
Example:
# ./prefix-file-script.sh

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-file-script.sh

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.

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap