Help with bash command to change lots of file names

Matthew Seaman m.seaman at plasm.demon.co.uk
Fri May 10 19:04:49 BST 2002


On Fri, May 10, 2002 at 03:19:20PM +0100, Peter McGarvey wrote:
> On Friday 10 May 2002 14:24 pm, Frank Shute wrote:
> > On Fri, May 10, 2002 at 02:17:49AM +0100, I wrote:
> > > On Thu, May 09, 2002 at 11:25:42PM +0100, greadey wrote:
> > > >     Hi peeps,
> > > >
> > > > I have a directory with lots of files called CHAPN.TXT where n is a
> > > > number from 1 to 14.  I want to turn them all into latex files and
> > > > so for ease of editing in Vim I want to change them all to chN.tex. 
> > > > I have been trying to write a bash command to do it with a for loop
> > > > and sed and I basically have;
> > > >
> > > > for f in *
> > > > do
> > > > NEW=`echo $f | sed -e 's/CHAP \( \W+ \. \) /ch \1 tex/ ' ` # I've
> > > > put whitespace in for clarity
> > > > #mv $f $NEW
> > > > echo $NEW
> > > > done
> > > >
> > > > I have tried different quotes and I believe my regexp is correct but
> > > > when I run this command or any variation I either get an error if I
> > > > use all single quotes instead of backticks and single quotes or the
> > > > command just prints all the original file names.
> > > >
> > > > Can someone tell me where I am going wrong?
> > > >
> > > > Thanks in advance
> > > >
> > > > greadey.
> > >
> > > I'm not wildly keen on your regex & I prefer brackets to backticks
> > > (more legible!). Try:
> > >
> > > NEW=$(echo $f | sed -e 's/CHAP\([1-9]*\)\.TXT/ch\1\.tex/')
> > >
> > > Works OK with /bin/sh (I think...) don't know about bash.
> >
> > I fouled up of course and I'd probably write the whole thing as:
> >
> > TARGET=$(ls -1 | grep 'CHAP[0-9]*.TXT')
> > for filename in $TARGET
> > do
> > NEW=$(echo $filename | sed -e 's/foo\([0-9]*\)\.txt/bogus\1\.tex/')
> > #mv $filename $NEW
> > echo $NEW
> > done
> >
> > Probably wrong again;) and if I had a choice I'd use perl rather than
> > shell.
> 
> 
> Once upon a time I'd have used perl too.  But I dislike writing 1-shot 
> scripts.  So I'd do it from the bash command line like this:
> 
> for f in `ls | grep CHAP.*\.TXT`; do mv -v $f `echo $f | sed 
> \-e's/CHAP\(.*\)\.TXT/ch\1.tex/'`; done

What --- write a script when you can do it as a (slightly long) one-liner?

perl -e 'for(@ARGV){($n = $_) =~ s/CHAP(\d+)\.TXT/ch$1.tex/; rename $_, $n;}' \
  CHAP*.TXT 

	Matthew

-- 
Dr Matthew J Seaman MA, D.Phil.                       26 The Paddocks
                                                      Savill Way
Tel: +44 1628 476614                                  Marlow
Fax: +44 0870 0522645                                 Bucks., SL7 1TH UK




More information about the Ukfreebsd mailing list