批量重命名文件、创建子文件夹以及按模式移动文件

批量重命名文件、创建子文件夹以及按模式移动文件

我的文件夹中有 500000 个文件,我想将它们移动到子文件夹中。这些子文件夹应该是自动创建的。

图案是{prefix}-{date}T{time}-{suffix}

文件夹结构应如下所示{date}/{time}/{suffix}

我已经设法用 bash 脚本删除前缀:

    #!/bin/bash
    for f in prefix-* ; do
        mv "$f" "${f/prefix-}"
    done

答案1

假设文件名称中不包含破折号-或大写字母T,您可以构建以下 bash 循环:

for f in *
do
   date=$(tmp=${f#*-};echo ${tmp%T*})
   time=$(tmp=${f#*T};echo ${tmp%-*})
   suffix=${f##*-}
   mkdir -p ${date}/${time}/${suffix}
   mv $f ${date}/${time}/${suffix}/
done

这是基本的 bash 参数扩展语法,根据手册页:

   ${parameter#word}
   ${parameter##word}
          Remove matching prefix pattern.  The word is expanded to produce a pattern just as in pathname expansion.  If the pat‐
          tern matches the beginning of the value of parameter, then the result of the expansion is the expanded value of param‐
          eter with the shortest matching pattern (the ``#'' case) or the longest matching pattern (the  ``##''  case)  deleted.
          If  parameter is @ or *, the pattern removal operation is applied to each positional parameter in turn, and the expan‐
          sion is the resultant list.  If parameter is an array variable subscripted with @ or *, the pattern removal  operation
          is applied to each member of the array in turn, and the expansion is the resultant list.

   ${parameter%word}
   ${parameter%%word}
          Remove matching suffix pattern.  The word is expanded to produce a pattern just as in pathname expansion.  If the pat‐
          tern matches a trailing portion of the expanded value of parameter, then the result of the expansion is  the  expanded
          value  of  parameter  with  the shortest matching pattern (the ``%'' case) or the longest matching pattern (the ``%%''
          case) deleted.  If parameter is @ or *, the pattern removal 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 pattern
          removal operation is applied to each member of the array in turn, and the expansion is the resultant list.

我使用了一个临时变量作为占位符,因为 bash 不允许直接嵌套扩展操作。

date=$(tmp=${f#*-};echo ${tmp%T*})
$f是当前文件名
tmp={f#*-}:删除第一个之前的所有内容(包括第一个)-
此时 tmp 保留{date}T{time}-{suffix}
${tmp%T*}:删除之后的所有内容T(包括)

相关内容