You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

bash脚本读取input.txt批量重命名文件的问题与解决

2022年12月1日更新

在triplee的建议下,我通过在f和d之间添加逗号,实现了同时处理文件和目录,最终代码如下:

while read -r old new; 
   do echo "replacing ${old} by ${new}" >&2 
   find '/path/to/dir' -depth -type d,f -name "$old" -exec rename 
   "s/${old}/${new}/" {} ';' 
done <input.txt

感谢帮助!


原始需求

我尝试将$homedir及其子目录中的一批文件从$old重命名为$new。

在命令行中,以下命令可实现子文件夹内的文件重命名:

find ${homedir}/ -name ${old} -exec rename "s/${old}/${new}/" */${old} ';'

但当我将该逻辑写入bash脚本,从input.txt读取$old和$new文件名时,脚本却无法正常工作……

input.txt内容如下:

name_old name_new
name_old2 name_new2
etc...

脚本内容如下:

#!/bin/bash
homedir='/path/to/dir'

cat input.txt | while read old new; 
do
    echo 'replacing' ${old} 'by' ${new}
    find ${homedir}/ -name ${old} -exec rename "s/${old}/${new}/" */${old} ';'
done

运行脚本后,echo语句正常输出所有$old与$new的替换提示,但没有文件被重命名,也无错误信息。我遗漏了什么?恳请您的帮助!

我已确认$old和$new变量已正确传递给find -exec rename命令(echo已正常打印),所以问题应该不在这。

内容的提问来源于stack exchange,提问作者Eva

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 23:25:35