linux - 脚本没有替换文件名的前缀

标签 linux bash shell

我正在尝试用另一个前缀(重命名)替换目录中所有文件的前缀。

这是我的脚本

# 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/

相关文章:

linux - 如何实现实用的光纤调度器?

python - 为什么 virtualenvwrapper 不能在 wing ide pro 终端内工作?

php - 如何在 PHP 中执行 linux 命令并以原始格式回显输出?

Linux 比较两个文本文件

linux - 根据unix中的模式将单行拆分为多行

linux - 如何从 bash 脚本启动程序,然后关闭终端但让程序保持事件状态

linux - 当输出到文件时 ls 的结果在一行中

php shell_exec 在后台一次执行多个命令

c - 如何将命令嵌入到作为内置命令的 bash 中?

string - bash:按当前出现次数/运行次数更改列字段