简体   繁体   English

帮助这个.sh代码

[英]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: 我正在尝试创建一个shell脚本,当您在终端中输入类似内容时,它会更改文件扩展名:

extcha xx yy *.xx 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. 你的最大缺陷是while循环只是评估那个条件,有效地测试了那个具有该形式名称的文件的存在。 It doesn't store anything in any variable - certainly not something arbitrary like $i . 它不会在任何变量中存储任何内容 - 当然也不像$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): 和花哨的perl one(debian / ubuntu):

rename 's/.foo$/bar/' *.foo

You could just use the rename utility... It does this. 你可以使用rename实用程序......它就是这样做的。

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) 不要忘记添加一些错误检查(例如,有两个参数)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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