tags:

views:

166

answers:

4

Hi, I would like to rename files numbering: I have a files with '???' format I need to put them in '????'.

myfile_100_asd_4 to myfile_0100_asd_4

Thanks Arman.

Not so elegant SOLUTION:

#/bin/bash
snap=`ls -t *_???`
c=26 
for k in $snap 
do 

     end=${k}
     echo  mv  $k ${k%_*}_0${k##*_}_asd_4
     (( c=c-1 ))

done

This works for me because I have myfile_100 files as well.

A: 

There's a UNIX app called ren (manpage) which supports renaming multiple files using search and substitution patterns. You should be able to cobble together a pattern that will inject that extra 0 into the filename.

Edit: Project page w/ download link can be found at Freshmeat.

slyfox
On my distribution (Mandriva) I have only :mren(1)Name mren - rename an existing MSDOS fileno ren.
Arman
I noticed that some distributions don't seem to ship with it, hence why I supplied a link to the Freshmeat page with a link to the source download.
slyfox
+4  A: 

Use rename, a small script that comes with perl:

rename 's/(\d{3})/0$1/g' myfile_*

If you pass it the -n parameter before the expression it only prints what renames it would have done, no action is taken. This way you can verify it works ok before you rename your files:

rename -n 's/(\d{3})/0$1/g' myfile_*
Martin
Hmm, it is soo pity that I cannot mark this as another solution:)
Arman
A: 

Try:

for file in `ls my*`
do
a=`echo $file | cut -d_ -f1`
b=`echo $file | cut -d_ -f2`
c=`echo $file | cut -d_ -f3,4`

new=${a}_0${b}_${c}
mv $file $new
done
codaddict
use shell expansion instead of `ls`. and shell has string manipulation capabilities so external commands are really not needed.
ghostdog74
ghostdog74: could you please explain more?
Arman
Wow, I never used the "cut", it is so useful :)
Arman
@modi, i am not the downvoter. don't be an ass yourself. and even if i want to down vote, its still my choice. what you gonna do about it?
ghostdog74
@arman, `cut` is an external command. Calling `cut` 3 times for each file found is "expensive".
ghostdog74
@ghostdog74, Thanks!
Arman
@ghostdog74, I'm SORRY if you aren't the down voter.A men took the time and tried to help.remarks are in order to help perfect his answer. it is your choice to down vote him and it my choice to call you an ass (if you are the down vote).
jojo
+3  A: 

just use the shell,

for file in myfile*
do
    t=${file#*_}
    f=${file%%_*}
    number=$(printf "%04d" ${t%%_*})
    newfile="${f}_${number}_${t#*_}"
    echo mv "$file" "$newfile"
done
ghostdog74
+1..good one...
codaddict
This is a nice solution thanks!
Arman