Tuesday, April 24, 2007

Change Filename Extensions with Inline Script

I want to quickly change the filename extensions for a directory with hundreds of *.dta files. The extension will be changed from *.dta to *.dat. I will use a simple inline script to accomplish the task. Also, I want to set the file to read all. Here's an example.

Change filename extension
# cd /directory_with_datafiles
# csh
# foreach filename ( *.dta )
?set base=`basename $filename .dta`
?mv $filename $base.dat
# chmod 444 *.dat

Here's an actual run
# csh
# touch t1.data t2.data t3.data t4.data t5.data
# foreach filename (*.data)
? set base=`basename $filename .data`
? mv $filename $base.dat
? end
# ls
t1.dat t2.dat t3.dat t4.dat t5.dat


Anonymous said...

For ksh:

for i in *.dta
mv $i ${i%%\.dta}.dat

esofthub said...

Thank you for your input anonymous.

Sitchai said...

find . -name "*.dta" | pax -rw -s '/\.dta$/\.dat/g' . ; rm -f *.dta

esofthub said...

Thanks sitchai!

Mathew Peet said...

There is a rename command in linux;

man rename says:
For example, to rename all files matching "*.bak" to strip the extension, you might say

rename 's/\.bak$//' *.bak

so your command would be something like;

rename 's/\.dta$/.dat/' *.dta