我正在尝试用另一个前缀(重命名)替换目录中所有文件的前缀。
这是我的脚本
# 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
视为相同的值,但是当我在另一行打印这些变量时,它显示它们是不同的。
最佳答案
正如 Roman Newaza 所说,您可以使用 "
而不是 '
来告诉 Bash 您希望扩展变量。但是,在您的情况下,这将是最安全的写:
for file in "$1"* ; do
mv -- "$file" "$2${file#$1}"
done
这样文件名或脚本参数中的奇怪字符就不会造成任何问题。
关于linux - 脚本没有替换文件名的前缀,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17207023/