Often in Bash you may want to rename the files in a particular folder to sequential numbers such as:
- 0001.txt
- 0002.txt
- 0003.txt
And so on.
You can use the following syntax to do so:
n=1; for i in *; do mv "$i" "$(printf '%04d' $n).${i#*.}"; ((n++)); done
This particular example will rename all files in the current directory to have the names 000.1txt, 0002.txt, 000.3txt, etc.
Note that by using the printf command with ‘%04d’ we are able to specify that the files should have enough leading zeros so that the total length of the filename is 4 characters.
Feel free to change 4 to a different number if you’d like the filenames to have a different length.
Note that the mv operator in Bash allows you to rename and move files.
In this example, we use the mv operator to rename the files while keeping the original extension for each file.
The following example shows how to use this syntax in practice.
Example: Rename Files in Folder to Sequential Numbers in Bash
We can use the ls command to first view all files in our current directory:
We can see that the current directory has the following files:
- coaches.txt
- owners.txt
- players.txt
- teams1.txt
- teams2.txt
Suppose that we would like to rename each of these text files to have sequential numbers as names instead.
We can use the following syntax to do so:
n=1; for i in *; do mv "$i" "$(printf '%04d' $n).${i#*.}"; ((n++)); done
The following screenshot shows how to use this syntax in practice:
Notice that when we use the ls command once again to view the updated filenames in the current directory we can see that the files now have the following names:
- 0001.txt
- 0002.txt
- 0003.txt
- 0004.txt
- 0005.txt
Note that each filenames has retained its original .txt file extension.
Feel free to use similar syntax to rename the files in your own folder using sequential numbers.
Related Tutorials
The following tutorials explain how to perform other common tasks in Bash:
Bash: How to Add Prefix to All Files in Directory
Bash: How to Replace Specific Text in Multiple Files
Bash: How to Replace Specific Line in File