Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How can i change one file extension to another? 2

Status
Not open for further replies.

ambili

Programmer
Aug 22, 2001
9
US
Hi,

I want to change the extension of a file to another. How can I do it using K shell script.
Thanks
Ambili
 
Not ksh:but mostly awk if you have it.

#!/bin/sh

ext="newextension"
#for current dir
bogus() {
targ=$1
echo $targ | awk -v x=$ext ' {
if ($0 ~ /\..*/) {
gsub(/\..*/,x,$0)
}
print
}'
}

for xx in *
do
new=`bogus $xx`
mv $xx $new
done


 
Using pure ksh:
Code:
old_ext=pl
new_ext=pm
for file in $(ls *.$old_ext)
do
    mv $file ${file%${old_ext}}${new_ext}
done
Look at the variable substitution commands in the ksh manual pages for more information:
Code:
${A%txt}  - removes 'txt' from end of $A
${A#test} - removes 'test' from front of $A

Hope this helps, Neil
 
Thanks for your help Neil. This is what I was looking for.

Thanks
Ambili
 
Neil,

Your script was just what I was looking for, but I have a couple of questions: I want to execute the script on files in several subdirectories and I can't seem to figure it out. I'm trying to use the script with the find command. Can you give me some hints?

My second question is when I execute a command and the shell returns something like: find: 0652-018: An expression term lacks a required parameter: what do the number 0652-018 mean and is there a resource to find the meaning and perhaps more help in what my syntax problem is?
 
Looks like you've got the find command a bit wrong, post your command and we'll have a look. Mike
michael.j.lacey@ntlworld.com
Email welcome if you're in a hurry or something -- but post in tek-tips as well please, and I will post my reply here as well.
 
Something like the following should do the trick:
Code:
old_ext=pl
new_ext=pm
find . -type f -name "*.$old_ext" -print | while read file
do
    mv $file ${file%${old_ext}}${new_ext}
done
The [tt]-f[/tt] option restricts the find to return regular files only, and [tt]-name[/tt] restricts the find to only those files ending with the old file extension.

Cheers, Neil :)
 
Toolkit, Yep. That did it. Thanks.

Mike, I didn't dow the "while" part as toolkit has in his script. Thanks.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top