hello, all
I have following files:
file_1 file_2 file_3 ... file_9
Now I want to rename them as:
file_001 file_002 file_003 ... file_009
how to use function 'rename' to accomplish this task?
hello, all
I have following files:
file_1 file_2 file_3 ... file_9
Now I want to rename them as:
file_001 file_002 file_003 ... file_009
how to use function 'rename' to accomplish this task?
The rename() function is a C language function; not a shell function. Since this is the Shell Programming and Scripting forum, I assume you want to rename files using shell commands. The mv utility (probably written in C on most Linux and UNIX implementations) usually uses the rename() function to perform its task (as long as you aren't moving a file onto a different file system).
For any POSIX conforming shell, the commands:
for i in file_[0-9]
do mv $i file_00${i#file_}
done
do what you want.
OP might have in mind the rename(1) utility, part of the util-linux package. There are a couple versions that I know of, the one on RedHat based systems has a manual of only one page and your exact problem with the solution is listed there, as an example:
Other systems use rename written in perl (sometimes called prename) which uses regexp syntax and have a useful -n switch (dry-run).
There it would be something like:
prename -n 's/_([0-9])\./_00$1./' file*
prename -n 's/_([0-9][0-9])\./_0$1./' file*
See manual page for your version.
A universal solution with the added educational benefits would be to use printf:
for i in file_* ; do
n=$(cut -d_ -f2 <<<$i)
echo mv $i file_$(printf "%03d" $n)
done