简体   繁体   中英

Help with this .sh code

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?

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

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM