如何通过在文件名中移动模式来重命名一组文件

How to rename a group of files by moving a pattern within the file names

对于文件

test_001.log
test_002.log

我想将它们重命名为

001_test.log
002_test.log

我觉得应该是这样的

for f in *.log; do mv "$f" "`echo $f | sed s/test_\(.*\)\.log/_test.log/`"; done

但我收到错误

mv: `test_001.log' and `test_001.log' are the same file

我做错了什么?

这是工作片段:

for f in *.log; do mv $f `echo $f | sed 's/test_\(.*\)\.log/_test.log/'`; done;

我认为您没有引用 's/test_\(.*\)\.log/_test.log/',这可能不会返回您期望的结果。

您只需 shell 参数扩展即可完成,无需外部工具:

$ for f in *.log; do fnew=${f#test_}; echo mv "$f" "${fnew%.log}"_test.log; done
mv test_001.log 001_test.log
mv test_002.log 002_test.log

删除 echo 以实际执行这些命令。

请注意,由于分词和路径扩展,命令中未加引号的 $f 可能会使包含空格或 shell 元字符的文件名中断。