In the manual pages rename(1)
, you can see an example to do that:
EXAMPLES
Given the files foo1, ..., foo9, foo10, ..., foo278, the commands
rename foo foo00 foo?
rename foo foo0 foo??
will turn them into foo001, ..., foo009, foo010, ..., foo278
So in your case, the simple solution (in case the maximum number is 3 digit long) would be:
rename file file00 file?.txt
rename file file0 file??.txt
Before run the actual rename
command, you can test it by adding --no-act / -n
and --verbose / -v
flags to see what would be the outcome:
$ rename -nv file file00 file?.txt
`file1.txt' -> `file001.txt'
`file2.txt' -> `file002.txt'
`file3.txt' -> `file003.txt'
$ rename -nv file file0 file??.txt
`file11.txt' -> `file011.txt'
`file12.txt' -> `file012.txt'
A more general solution (available since bash
version 3.0):
$ for i in `find ./ -maxdepth 1 -type f -name 'file*.txt'`; \
do if [[ "$i" =~ file([0-9]*).txt$ ]]; \
then NUM=$(printf "%03d" "${BASH_REMATCH[1]}"); \
echo mv --verbose $i $i ./file${NUM}.txt; \
fi; \
done
mv --verbose ./file1.txt ./file001.txt
mv --verbose ./file2.txt ./file002.txt
mv --verbose ./file3.txt ./file003.txt
mv --verbose ./file11.txt ./file011.txt
mv --verbose ./file12.txt ./file012.txt
mv --verbose ./file100.txt ./file100.txt
mv --verbose ./file101.txt ./file101.txt
Remove the echo
when you want to perform the change. It's just a simple example, you can change the prefix and suffix of the files to patterns as well in the if
line, and use $BASH_REMATCH
to capture those to make more complex renames. For instance:
$ for i in `find ./ -maxdepth 1 -type f`; \
do if [[ "$i" =~ ^([^0-9]*)([0-9]*).txt$ ]]; \
then NUM=$(printf "%03d" "${BASH_REMATCH[2]}"); \
echo mv --verbose $i ${BASH_REMATCH[1]}${NUM}.txt; \
fi; \
done
mv --verbose ./file1.txt ./file001.txt
mv --verbose ./file2.txt ./file002.txt
mv --verbose ./file3.txt ./file003.txt
mv --verbose ./file11.txt ./file011.txt
mv --verbose ./file12.txt ./file012.txt
mv --verbose ./file100.txt ./file100.txt
mv --verbose ./file101.txt ./file101.txt
mv --verbose ./something1.txt ./something001.txt
mv --verbose ./another02.txt ./another002.txt
Of course in the you can modify the printf
command to change the zero padding length from 3 to any other number.
file
) and the suffix (.txt
) always the same?