Web Hosting Talk







View Full Version : Linux: Changing Multiple File Extensions


allan
12-16-2001, 12:51 PM
Do any of you know off the top of your head how to change multiple file extensions at the same time.

I have about 20 files that have the .php3 extension, and I want to change them to .php files. I know it can be done, but so far I have not been able to figure it out using cp or mv.

allending
12-16-2001, 03:31 PM
allan,

#!/usr/bin/perl
# CopyLeft 2000 David Correa tech@linux-tech.com

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA


# usage example: change /home/htdocs/ .php3 .php
# This PERL script will change the extention
# of mutiple files in a directory

$path = @ARGV[0] . "*";
$path = $path . @ARGV[1];
@a = glob("$path");
foreach $temp (@a) {
@var2 = split(/./,$temp);
$oldname = @var2[0] . @ARGV[1];
$newname = @var2[0] . @ARGV[2];
rename ("$oldname" , "$newname");
}

bitserve
12-16-2001, 03:33 PM
I know how to do it on one line with a script and sed.


for f in *.php3; do mv "$f" "$(echo $f | sed s/.php3$/.php/)"; done

CRego3D
12-16-2001, 04:19 PM
Dammit, don't you miss MS-DOS ? .. it would have taken only this command "copy *.php3 *.php"

haa, the good old days :D

CRego3D
12-16-2001, 04:21 PM
humm actually "ren *.php3 *.php" :)

allan
12-16-2001, 11:49 PM
Thanks for all of the replies guys, and I always miss DOS Carlos :).

Allen -- I actually had trouble getting your script to work, but I took the idea and kind of made my own. This is not the first time I have had this problem, but now that I have a solution, I figure it will be useful to keep around:


#!/usr/bin/perl
#
# Usage: ./frename
print "This script swaps extensions for files in a directory. \n";
print "What is the full path (without the /) to the directory? \n";
$dir = <STDIN>;
chomp ($dir);
print "What is the current file extension (include the .)? \n";
$ext1 = <STDIN>;
chomp ($ext1);

print "What is the new file extension (include the .)? \n";
$ext2 = <STDIN>;
chomp ($ext2);

# That's it! Be sure to chmod the script to 744 and run it from the
# command line.
###################
opendir(FILES,"$dir");
@allfiles = grep(!/^\.\.?$/,readdir(FILES));
closedir(FILES);
foreach $file(@allfiles){
$newfile = $file;
$newfile=~ s/$ext1/$ext2/g;
rename("$dir/$file","$dir/$newfile");
}
exit;


Not pretty, but it works for me.

allending
12-16-2001, 11:57 PM
Thanks, I have it saved :D