2013-06-20 56 views
1

我想用另一个前缀(重命名)替换目录中所有文件的前缀。脚本不替换文件名的前缀

这是我的脚本

# Script to rename the files 
#!/bin/bash 
for file in $1*; 
do 
    mv $file `echo $file | sed -e 's/^$1/$2/'`; 
done 

在与

rename.sh BIT SIT 

执行脚本我收到以下错误

mv: `BITfile.h' and `BITFile.h' are the same file 
mv: `BITDefs.cpp' and `BITDefs.cpp' are the same file 
mv: `BITDefs.h' and `BITDefs.h' are the same file 

好像sed是治疗$1$2一样价值,但是当我p在另一行上打印这些变量表明它们不同。

+0

不要忘了接受低于他们是否帮助你:-) –

回答

3

正如Roman Newaza所说,您可以使用"而不是'告诉Bash您希望扩展变量。然而,在你的情况,这将是最安全的写:

for file in "$1"* ; do 
    mv -- "$file" "$2${file#$1}" 
done 

所以在那个文件名字符怪异,或在你的脚本参数,不会引起任何问题。

+0

感谢,它完美地 –

+0

工作@ rahul.deshmukhpatil的解决方案之一:不客气! – ruakh

0

使用双引号来代替:

# ... 
mv "$file" `echo $file | sed -e "s/^$1/$2/"` 
# ... 

而且在猛砸学习Quotes and escaping

0

当您不使用双引号时,变量将不会展开。

我宁愿用这个

#!/bin/bash 
for file in $1*; 
do 
    mv "$file" "$1${file:${#2}}" 
done 

其中

${file:${#2} 

意味着子,从参数2的长度到底

2

您还可以使用parameter expansion更换前缀目录中所有文件的

for file in "$1"*; 
do 
    mv ${file} ${file/#$1/$2} 
done 
+1

你想用'“$ 1”*'来避免[分词](http://mywiki.wooledge.org/WordSplitting)。 – l0b0

+0

@ l0b0 true;固定。 – devnull

+3

这个例子很好,但是在文件名空白的情况下,将'mv'的两个参数加双引号可能是一个好主意。 – doubleDown