Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rename several files in the BASH

Tags:

bash

renaming

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.

like image 370
Arman Avatar asked Dec 10 '22 17:12

Arman


2 Answers

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_*
like image 191
Martin Avatar answered Dec 30 '22 11:12

Martin


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
like image 35
ghostdog74 Avatar answered Dec 30 '22 09:12

ghostdog74