1. Overview

One common task is to rename files in batches. We often need to follow a particular naming convention while renaming files. In our case, the requirement is that we have a set of files whose names (before the extension) are numbers, and each file name should be a four-digit number. If the number is smaller, then we should add leading zeros to file names.

In this tutorial, we’ll look at some of the ways to accomplish this in bash.

2. Setup

Let’s create a few sample files to use as an example:

$ touch 1.txt 02.txt 123.txt 1234.txt
$ ls -1
02.txt
1234.txt
123.txt
1.txt

3. By Extracting the Filename and Extension

In bash, we can use parameter expansion to extract the filename and its extension. Using this technique, we can achieve the desired result:

$ for file in [0-9]*.txt;
do
name=${file%.*}
extension=${file##*.}
new_name=`printf %04d.%s ${name} ${extension}`
mv -n $file $new_name
done
$ ls -1
0001.txt
0002.txt
0123.txt
1234.txt

In the above example, we’ve used the %04d format specified with the printf command. It adds leading zeros to a number to make it a four-digit number.

4. Using the rename Command

rename is a simple command that renames multiple files. However, the special thing about it is that it allows us to specify a rule as an argument. Let’s understand this with an example:

$ rename 'unless (/0+[0-9]{4}.txt/) {s/^([0-9]{1,3}\.txt)$/000$1/g;s/0*([0-9]{4}\..*)/$1/}' *
$ ls -1
0001.txt
0002.txt
0123.txt
1234.txt

In the above example, the unless rule specifies that we process all text files whose name is not a four-digit number. The next block uses a regular expression that adds leading zeros to the file names and renames the files accordingly.

5. Using the awk and xargs Commands

We can also use the combination of the awk and xargs commands to add leading zeros to the file names:

$ ls | awk '/^([0-9]+)\.txt$/ { printf("%s %04d.txt\n", $0, $1) }' | xargs -n2 mv -n
$ ls -1
0001.txt
0002.txt
0123.txt
1234.txt

In this example, we’ve used the awk command’s printf function to generate a file name with leading zeros. It prints the original and new file name on the standard output stream. Then, the xargs command converts them to command-line arguments and passes them to the mv command.

6. Conclusion

In this article, we discussed some of the practical examples to add leading zeros to file names. First, we used the bash shell’s parameter expansion. Then, we saw an example using the rename command. Finally, we demonstrated a solution using the combination of awk and xargs commands.

Comments are closed on this article!