用于批量重命名文件夹中文件的 Shell/Bash 快捷方式 [英] Shell/Bash shortcut for bulk renaming of files in a folder
问题描述
Shell/Bash 中是否有快捷方式可以根据正则表达式或其他一些条件重命名文件夹中的所有文件.我在这里寻找的是在我的文件夹文档中,假设有 100 个具有以下命名约定的文本文件:
Is there a shortcut in Shell/Bash that can rename all the files in a folder based on a regex or some other criteria. What I am looking for here is in my folder documents, that has let's say a 100 text files with the following naming convention:
<longdocumentidentifier>-doc-<counter>.txt.
我需要使用上述给定的约定将所有文件重命名为:
I need to rename all the files with the above given convention to just:
doc-<counter>.txt
有没有可以帮助我解决上述问题的单线?
Is there a one-liner that can help me with the above?
推荐答案
我的建议是这样的:
for i in *-doc-*.txt; do mv "$i" "${i/*-doc-/doc-}"; done
${i/*-doc-/doc-}
将第一次出现的 *-doc-
替换为 doc-
.
${i/*-doc-/doc-}
replaces the first occurrence of *-doc-
with doc-
.
如果您需要进行多次替换(请参阅注释编号 1),则需要使用 ${var//Pattern/Replacement}
变体.如果需要替换名称的开头需要使用${var/#Pattern/Replacement}
,如果需要替换结尾(即:扩展名)需要使用<代码>${var/%Pattern/Replacement} 形式.
If you need to do more than one replacement (see comment number 1), you need to use the ${var//Pattern/Replacement}
variant. If you need to replace the beginning of the name you need to use ${var/#Pattern/Replacement}
, if you need to replace the end (ie: the extension) you need to use the ${var/%Pattern/Replacement}
form.
参见 Shell 参数扩展更多细节.此扩展是特定于 bash 的.
See Shell Parameter Expansion for more details. This expansion is bash specific.
这篇关于用于批量重命名文件夹中文件的 Shell/Bash 快捷方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!