Operating System - HP-UX
1844205 Members
2656 Online
110229 Solutions
New Discussion

need shell script to rename files in a directory

 
SOLVED
Go to solution
Ratzie
Super Advisor

need shell script to rename files in a directory

I need a shell script to rename files in a certain directory.

Actually preface all files with an entry.

These files have spaces in them too. (Camera pics)

So instead of:
beach drinks.jpg

Maybe something like:

0501 CUBA beach drinks.jpg
4 REPLIES 4
Mel Burslan
Honored Contributor

Re: need shell script to rename files in a directory

cd /my/directory
for file in `ls -1`
do
newname="0501_CUBA"${file}
mv $file $newname
done
________________________________
UNIX because I majored in cryptology...
Mel Burslan
Honored Contributor
Solution

Re: need shell script to rename files in a directory

sorry I did not notice the filenames has spaces comment, so my previous suggestion was useless but this one should do the magic

cd /my/directory
ls -1 | while read filename
do
newname="0501 CUBA "${filename}
mv "${filename}" "${newname}"
done


HTH
________________________________
UNIX because I majored in cryptology...
Simon Hargrave
Honored Contributor

Re: need shell script to rename files in a directory

You can use IFS variable to change the shell's Input Field Separator to be "return" instead of "space".

IFS="
"
for file in *
do
mv "$i" "0501 CUBA $i"
done


If you run this interactively in your current shell rather than in a script you'll want to save then retrieve the IFS variable, so before you start: -

OIFS=$IFS

Then when you've done: -

IFS=$OIFS

Ratzie
Super Advisor

Re: need shell script to rename files in a directory

Thanks, worked like a charm