On Sat, 27 Feb 1999, Ken Lai wrote:
> Say I want to rename files in a directory to change spaces to "_":
>
> I've tried using a "for" construct in bash and tcsh, but neither could
> catch the whole filename. e.g.
>
> # bash:
> for FILE in *; do
> ls $FILE
> done
I'll address 'sh' because nobody really writes scripts for tcsh. You're
actually *really* close here. What you haven't yet realized is that
for FILE in *
does actually extract individual files and deal with spaces correctly.
What you're forgetting is that when you actually *use* something with
spaces in it, you need to quote it. So the following modification should
work:
#!/bin/sh
for FILE in *
do
ls "$FILE"
done
Or, if you actually want to rename them the way you suggested:
#!/bin/sh
for FILE in *
do
NEW=`echo $FILE | sed 's/ /_/g'`
if [ "$FILE" != "$NEW" ]
then
mv "$FILE" $NEW
fi
done
This is basically the sh-equivalent of Matt's script, except that it
checks to make sure that the file's name isn't identical to its target.
That's just an aesthetic thing; it should work in the shell or in Perl the
same without that check, more or less.
Shawn
(get ready for a whole barrage of messages, now, if I have the
energy...) :)