[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: how do I write a shell script to batch rename files in a directory?
From: |
Bob Proulx |
Subject: |
Re: how do I write a shell script to batch rename files in a directory? |
Date: |
Fri, 29 Aug 2008 14:51:51 -0600 |
User-agent: |
Mutt/1.5.13 (2006-08-11) |
Tony Zanella wrote:
> I have a directory listing of files like:
> img.bc03.547.1.gif?
> I need to trim the last character off for each file in the dir.
> I know I can use:
> mv img.bc03.547.1.gif? img.bc03.547.1.gif
> to rename each by hand, but I want to do this as a batch.
> I know it would start with:
> for files in *; do;
> after that, I'm stuck!
> Any suggestions?
The easiest way is to use the 'rename' command which is usually
installed as part of Perl.
rename --verbose 's/.gif\?$/.gif/' *.gif?
But bash can of course be used to write a small command line program
to do this too. Here is one way (there are many):
for i in *.gif?; do mv --verbose $i ${i%\?}; done
See the bash manual section "Parameter Expansion" for more information
on doing bash substitution.
${parameter%word}
${parameter%%word}
The word is expanded to produce a pattern just as in pathname
expansion. If the pattern matches a trailing portion of the
expanded value of parameter, then the result of the expansion is
the expanded value of parameter with the shortest matching pat-
tern (the ‘‘%’’ case) or the longest matching pattern (the
‘‘%%’’ case) deleted. If parameter is @ or *, the pattern
removal operation is applied to each positional parameter in
turn, and the expansion is the resultant list. If parameter is
an array variable subscripted with @ or *, the pattern removal
operation is applied to each member of the array in turn, and
the expansion is the resultant list.
Bob