cancel
Showing results for 
Search instead for 
Did you mean: 

rename files

SOLVED
Go to solution
Michael_33
Regular Advisor

rename files

Hi All,

I want to rename all *.png files to *.gif under /opt
directory, how can I do?

Thanks!
7 REPLIES
Solution

Re: rename files

Hi

It is a kind of brut force solution but anyway
# cd /opt
# for i in *.png
> do
> mv $i `echo $i|awk -F '.png' '{print $1}`.gif
> done;
Olav Baadsvik
Esteemed Contributor

Re: rename files

Hello,
here is one way of doing it.
First execute this command:

find /opt -name ?\*.png -exec ls {} \; > /tmp/png_files

Then inspect the file /tmp/png_files to
make sure that you really want to rename all
files in it.
Then run this command
cat /tmp/png_files | rename_script

where the rename_script looks like this
#!/bin/ksh while read filnavn
do
echo $filnavn
new=`echo $filnavn | sed s/.png$/.gif/`
echo $new
mv $filnavn $new
done

Peter Kloetgen
Esteemed Contributor

Re: rename files

Hi Michael,

you should solve this problem with a loop construction:

mkdir /tmp/renamer
cd /opt
ls . *.png | cp /tmp/renamer
cd /tmp/renamer
for i in `ls /tmp/renamer/*
do
mv $1 `echo $i | sed s/.png/.gif/`
done
# Please check here, if the result is what you
# want. If the answer is yes, remove the files # which you no longer need
rm -f /opt/*.png
# after this, copy the files to /opt and
# delete the /tmp/renamer
cp /tmp/renamer/*.gif /opt
rm -rf /tmp/renamer
# show the effect
ls /opt/*.gif

Allways stay on the bright side of life!

Peter
I'm learning here as well as helping
Tom Geudens
Honored Contributor

Re: rename files

Hi,
You could do that with the following script ... replace the echo by the actual command ...

#!/usr/bin/sh
for i_file in $(find /opt -name *.png)
do
o_file=$(echo $i_file | awk ' { sub(".png",".gif",$1) ; print $1 } ')
echo "mv $i_file $o_file"
done

Hope this helps,
Tom Geudens
A life ? Cool ! Where can I download one of those from ?
Robin Wakefield
Honored Contributor

Re: rename files

Hi Michael,

find /opt -type f -name "*.png" | while read file ; do
echo mv $file ${file%.png}.gif
done

This will preview the action. Remove the echo to actually run it.

Rgds, Robin.

Re: rename files

Just two cents more. Both arguments of mv comand should be quoted by double quotes. Sorry for my french. I mean
mv "$oldname" "$newname"
Michael_33
Regular Advisor

Re: rename files

Thanks all! :-)