Afficher un message
Vieux 02/09/2007, 19h39   #10
Chris F.A. Johnson
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: Batch file rename in Linux (consecutive numbers)

On 2007-09-02, arch119 wrote:
> On Sep 2, 1:33 am, spce...@armory.com (John DuBois) wrote:
>> In article <1188589094.698861.37...@i38g2000prf.googlegroups. com>,
>>
>> gibbonsp <gibbo...@gmail.com> wrote:
>> >I need to rename a batch of files:

>>
>> >foo_001.jpg
>> >foo_002.jpg

....
>> >....and so on.

>>
>> >I need to take the number on these files (notice how the number is
>> >duplicated on foo and bar) and make the entire batch consecutive. In
>> >other words, I want the file list to look like this:

>>
>> >foo_001.jpg
>> >foo_002.jpg

....
>> >....and so on.

>>
>> >I'd appreciate any ideas! I just feel like this is so simple and I'm
>> >just not seeing the answer!

>
> Assuming that your filenames follow the pattern .*_¥d{3}.jpg
>
> #!/bin/bash
>
> #dir files contains all the files
> files=`ls files`
> i=1
> padding="000"
> for file in $files


That is an unsafe way to loop through files; ls is unnecessary and
will break the script if any filenames contain spaces or other
pathological characters. Use:

for file in *

> do
> ((len=3-${#i}))


That is non-standard syntax for shell arithmetic; use the standard:

len=$(( 3 - ${#i} ))

> j="${padding:0:${len}}${i}"


That is non-standard. Use a case statement for portability:

case ${#i} in
0) j=000 ;;
1) j=00$1 ;;
2) j=0$i ;;
*) j=$i ;;
esac

> newName=${file/_???./_${j}.}
> mv files/${file} files/${newName}


That will break if any filenames contain spaces, etc. Quote the
variables:

mv "files/$file" "files/$newName"

> ((i=i+1))


See previous note on arithmetic.

> done




--
Chris F.A. Johnson, author <http://cfaj.freeshell.org/shell/>
Shell Scripting Recipes: A Problem-Solution Approach (2005, Apress)
===== My code in this post, if any, assumes the POSIX locale
===== and is released under the GNU General Public Licence
  Réponse avec citation
 
Page generated in 0,06662 seconds with 9 queries