1837097 Members
2248 Online
110112 Solutions
New Discussion

Re: rename script.

 
Vlad_11
Frequent Advisor

rename script.

Hi,
it's help call rather than a question, I trying to write a script that will rename all files in given /mydir/ into inremented by +1 numeric name. Like
file012.dat 101.dat
file333.dat 102.dat
file4.xls 103.xls

I'm on HPUX, thoug probably I will need to run this on PC (after installing Perl) or just under DOS??

Thanks all
Dai
beer or not beer
2 REPLIES 2
Rodney Hills
Honored Contributor

Re: rename script.

Here is a ksh script that should work. It goes through all the files in a directory and creates a "mv" statement to rename.

I prefer a script that creates another script so that it gives me a chance to review the "mv" commands.

I also recommend moving the files to another directory. If you move into the same directory you have the potential of renaming a file to a name that already exists.

#!/usr/bin/ksh
typeset -Z3 cnt=0
cd /your/path
ls -1 >/tmp/files
while read line ; do
let "cnt = cnt + 1"
echo "mv '$line' '../newloc/${cnt}.${line##*.}'"
done /tmp/moveit

File /tmp/moveit will be a list of "mv" commands. Enter "sh /tmp/moveit" to run.

HTH

-- Rod Hills
There be dragons...
BONNAFOUS Jean Marc
Trusted Contributor

Re: rename script.

Hi,

cd /mydir
NUMBER=100
for file_name in `ls`
do
endname=`echo $file_name|cut -d'.' -f2`
mv $file_name "$NUMBER.$endname"
NUMBER=`expr $NUMBER + 1`
done

Be sure what no directory is present in /mydir else you must to add test if file_name is a directory or not before rename it

Rgds
JMB
Si vous ne faites jamais de bétises, c'est que vous ne faites rien de difficile. Et ça c'est une grosse bétise.