[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: batch renaming for filenames with space



On Mon, Jul 28, 2003 at 04:37:01PM -0400, David Z Maze wrote:
> Micha Feigin <michf@math.tau.ac.il> writes:
> > I am trying to do a batch rename for a bunch of files with spaces in the
> > name (in order to remove the spaces actually). I tried to use bash's for
> > .. in command but it splits up the lines on spaces and not on line ends.
> > Any ideas?
> >
> > The files are named "Copy of ..." and I want to drop the Copy of part.
> > I tried to do
> > for file in `ls -1`; do 
> >   cp $file `echo -n "$file" | sed 's/Copy of \(.*\)/\1/'`
> > done
> 
> You pretty much never want to do `ls` in a shell script; * has the
> same effect, saves a process, and is somewhat more predictable in
> terms of filename-to-shell-word mapping.  You also need to be careful
> about quoting $file when you use it.  Thus, I'd try something like
> 
> for file in *; do
>   cp "$file" `echo "$file" | sed 's/^Copy of//'`
> done
> 
> I think you get no guarantees if $file is "Copy of my file.doc",
> though; you might need something like
[...]

I think what you want then is an extra level of double quotes around the
backticks, thus:

  for file in *; do
    cp "$file" "`echo "$file" | sed 's/^Copy of//'`"
  done

This is untested, though.

Cheers,

-- 
Colin Watson                                  [cjwatson@flatline.org.uk]



Reply to: