Skip site navigation (1)Skip section navigation (2)
Date:      Fri, 10 Jan 2003 01:49:18 +1030 (CST)
From:      Rob <rob@deathbeforedecaf.net>
To:        "BigBrother (BigB3)" <bigbrother@bonbon.net>, "Duncan Anker" <d.anker@au.darkbluesea.com>
Cc:        freebsd-questions@freebsd.org
Subject:   Re: Renaming files with spaces in the name to files without spaces..                                                       
Message-ID:  <200301091519.h09FJIK7000567@goo.0x7e.net>
In-Reply-To: <1042068862.1441.3.camel@duncan.au.darkbluesea.com>
References:  <1042068862.1441.3.camel@duncan.au.darkbluesea.com>, <20030108175539.W65616@bigb3server.bbcluster.gr>

next in thread | previous in thread | raw e-mail | index | archive | help
> > Sorry for this OT but I am trying for some hours to achieve a massive
> > rename of files using a simple script and I have not success yet. I want
> > to rename files like
> >
> > "RESULTS OF JAN 01 2002.txt "
> >
> > to
> >
> > "RESULTS_OF_JAN_01_2002.txt"
> >
> > i.e. all the spaces, being substituted by '_', and the last space being
> > completely removed [yes it has a space after the suffix]
> > I tried to experiment with sed/awk and creating a sample sh script with
> > for i in 'ls' ....
> >
> > but the i takes values of 'RESULTS' 'OF' 'JAN'. This means that it doesnt
> > take the full filename as value, but parts of the filenames.
> >
> >
> > Can u please suggest an easy way to implement the massive rename?
> >
>
> If you want to do it for all files in a directory:
>
> # for file in *; do mv "$file" `echo $file | sed -e 's/ /_/g'`; done
>
> should do the trick. I think Perl is overkill for something this simple.
> Someone else suggested tr, which probably works, but I've had more
> success with sed.

But if you do this, won't the spaces be mistaken for filename separators?

Try this instead - make sure you're using sh, not csh:

  ls *\ * | while read OLD ; do
    NEW=`echo $OLD | tr ' ' _`
    echo mv -i $OLD $NEW
    done

This works because ls prints them on separate lines. Once you're sure that it
will do the right thing, take out the echo and run it for real.

If the files are all over the place, you can use find the same way:

  find * -name '* *' -type f | while read OLD ; do
    NEW=`echo $OLD | tr ' ' _`
    echo mv -i $OLD $NEW
    done

You'll have to fix the directories separately (otherwise find gets lost).


To Unsubscribe: send mail to majordomo@FreeBSD.org
with "unsubscribe freebsd-questions" in the body of the message




Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?200301091519.h09FJIK7000567>