如何重命名多个文件?

How to rename multiple files?

在一个文件夹中我有几个具有以下名称结构的文件(我只写了三个例子):

F_001_4837_blabla1.doc
F_045_8987_blabla2.doc
F_168_9092_blabla3.doc

我会做的是使用 BASH 命令通过删除第一个下划线和获得第一个数字代码之前的一系列零来重命名我文件夹中的所有文件:

F1_4837_blabla1.doc
F45_8987_blabla2.doc
F168_9092_blabla3.doc
shopt -s extglob

for f in *; do
  echo "$f: ${f/_*(0)/}"
  # mv "$f" "${f/_*(0)/}"   # for the actual rename
done

输出

F_001_4837_blabla1.doc: F1_4837_blabla1.doc
F_045_8987_blabla2.doc: F45_8987_blabla2.doc
F_168_9092_blabla3.doc: F168_9092_blabla3.doc

参数扩展

参数扩展可用于替换变量的内容。在这种情况下,我们将模式 _*(0) 替换为空

${parameter/pattern/string}
       Pattern substitution.  The pattern is expanded to produce a pat-
       tern just as in pathname expansion.  Parameter is  expanded  and
       the  longest match of pattern against its value is replaced with
       string.  If pattern begins with /, all matches  of  pattern  are
       replaced   with  string.   Normally  only  the  first  match  is
       replaced.  If pattern begins with #, it must match at the begin-
       ning of the expanded value of parameter.  If pattern begins with
       %, it must match at the end of the expanded value of  parameter.
       If string is null, matches of pattern are deleted and the / fol-
       lowing pattern may be omitted.  If parameter is @ or *, the sub-
       stitution  operation  is applied to each positional parameter in
       turn, and the expansion is the resultant list.  If parameter  is
       an  array  variable  subscripted  with  @ or *, the substitution
       operation is applied to each member of the array  in  turn,  and
       the expansion is the resultant list.

扩展模式匹配

扩展模式匹配允许我们使用模式 *(0) 来匹配零个或多个 0 字符。它需要使用 extglob 设置启用。

If the extglob shell option is enabled using the shopt builtin, several
extended pattern matching operators are recognized.  In  the  following
description, a pattern-list is a list of one or more patterns separated
by a |.  Composite patterns may be formed using one or more of the fol-
lowing sub-patterns:

       ?(pattern-list)
              Matches zero or one occurrence of the given patterns
       *(pattern-list)
              Matches zero or more occurrences of the given patterns
       +(pattern-list)
              Matches one or more occurrences of the given patterns
       @(pattern-list)
              Matches one of the given patterns
       !(pattern-list)
              Matches anything except one of the given patterns