Reputation: 1299
I'm trying to create a shell script that will change a file extenstion when you type something like this into the terminal:
extcha xx yy *.xx
This is the code I produced
#!/bin/sh
while [ *.$1 ] ; do
export name=`basename $i .$1`
echo mv $name.$1 $name.$2
done;
This doesn't seem to work. Can someone tell me where i'm going wrong?
Upvotes: 0
Views: 216
Reputation: 91270
You could just use the rename
utility... It does this.
EDIT: The script.
#!/bin/bash
from="$1"
shift
to="$1"
shift
IFS="
"
for f in $@
do
basefile="`basename "$f" ".$from"`"
if [ ! "$basefile" = "$f" ]
then
echo mv "$basefile.$from" "$basefile.$to"
fi
done
Upvotes: 0
Reputation: 496902
Here is what you mean to do:
for name in *.$1; do
stripped_name="$(basename "$name" ".$1")"
mv "$name.$1" "$name.$2"
done
The big flaw in yours is that the while loop just evaluates that condition, effectively testing for the existence of files with names of that form. It doesn't store anything in any variable - certainly not something arbitrary like $i
. You also needn't export anything here. That just makes it visible to child processes, which you don't need.
Of course, you could really just use a rename utility. With the basic one (redhat and friends):
# Note that this will actually rename abc.foo.foo to abc.bar.foo
# since it replaces the first match.
rename .foo .bar *.foo
and with the fancy perl one (debian/ubuntu):
rename 's/.foo$/bar/' *.foo
Upvotes: 2
Reputation: 14376
Change to:
for i in *.$1 ; do
name=`basename $i .$1`
mv $name.$1 $name.$2
done
Don't forget to add some error checking (that there are two arguments for example)
Upvotes: 0