Does this work? [closed]
I haven't got Linux on my computer at the moment, so I was wondering if someone can test this code I wrote.
It is supposed to rename a file extension when you type something like this, to run it, into the terminal:
chaxxx zzz yyy *.zzz
"chaxxx" being the name of the file.
Here's the code I wrote:
>>deleted<<
Use an online compiler & interpreter for your tests. ideone supports Bash Script too.
EDIT:
It does work. ren.sh is your script name, here you go:
$ ls
asdf.doc ren.sh text.txt
$ ./ren.sh txt doc *.txt
text.txt
text
$ ls
asdf.doc ren.sh text.doc
Have you looked at the rename
command? You are pretty much reinventing the wheel here.
From man rename
rename .htm .html *.htm
will fix the extension of your html files.
Edit
If you are going to do it yourself in bash
then I would suggest the following code instead. Here are its benefits:
- It handles files with spaces in their names
- It checks to see if the file it's about to modify actually
ends in the extension you want to
change before it attempts to
mv
it. - It uses native Parameter Expansion syntax rather than call the external binary
basename
- It checks to see if the # of input parameters is at least 3, otherwise it echos a usage message and exits
- It uses a for-loop with indirection rather than calling the
test
withshift
#!/bin/bash
if (( $# < 3 )); then
echo "Usage: $0 oldExt newExt files"
exit
fi
EXTf=$1
EXTt=$2
for (( i = 3; i <= $#; i++)); do
NAME=${!i}
if [[ "${NAME##*.}" == "$EXTf" ]]; then
mv "$NAME" "${NAME%.*}.$EXTt"
fi
done
精彩评论