【发布时间】:2012-12-31 11:32:09
【问题描述】:
我的目录有很多文件,命名为“20130101_temp.txt”、“20130102_temp.txt”等。
如何删除所有这些文件名称中的“_temp”。即,将 20130101_temp.txt 重命名为 20130101.txt。
【问题讨论】:
标签: bash
我的目录有很多文件,命名为“20130101_temp.txt”、“20130102_temp.txt”等。
如何删除所有这些文件名称中的“_temp”。即,将 20130101_temp.txt 重命名为 20130101.txt。
【问题讨论】:
标签: bash
试试这样的:
for FILENAME in *_temp.txt; do
mv $FILENAME `echo $FILENAME | sed -e 's/_temp//'`
done
最好先尝试一下,将mv 替换为echo。
【讨论】:
使用 bash:
for x in *_temp.txt
do
mv $x ${x%%_temp.txt}.txt
done
Perl(至少在 Ubuntu 上)还有一个名为 rename 的实用程序,它采用正则表达式,因此您可以通过以下方式完成相同的操作:
rename -n 's/_temp\.txt$/.txt/' *_temp.txt
-n 选项会启动“试运行”,它只会向您显示要重命名的内容。删除它以实际执行重命名。
【讨论】:
使用带有 glob 的 for-loop 来查找文件并使用 parameter substitution 删除 _temp 以进行移动:
for t in ????????_temp.txt; do
echo mv ${t} ${t/_temp/}
done
当您测试输出在您的系统上看起来正确时,删除 echo。
【讨论】:
这不是一个 bash 解决方案,但由于我经常遇到重命名任务,同时懒得考虑一个合理的 bash 解决方案,所以我刚刚得到了 pyRenamer,这是一个可以很好地完成类似事情的 GUI 工具。它通常可以从标准存储库安装。
dlundquist 的解决方案效果很好。
【讨论】:
这对我有用:
find . -depth -name '*_temp*' -execdir bash -c 'for f; do mv -i "$f" "${f//_temp/ }"; done' bash {} +
【讨论】: