Batch 从文件名中获取一部分,并使用此部件创建一个文件夹



>我有这样命名的文件:

414_gtmlk_videos_Mas_147852_hty1147.xls
414_gtmlk_videos_Mas_P147852_hty1147.txt

我想创建一个作业来检查文件名并获取文件名中Mas后的部分 (147852-P147852(并使用此部件名称创建一个文件夹(文件夹名称应为:147852-P147852(。最后将每个文件移动到他的文件夹中。

Batch 从文件名中获取一部分并使用此部分创建一个文件夹,我有如下名称的文件: 414_gtmlk_videos_Mas_147852_hty1147.xls 414_gtmlk_videos_Mas_P147852_hty1147.txt(文件夹名称将为 这里:147852-P147852(

这是一种使用批处理脚本执行此操作的方法,因为您在问题中将其标记为batch-file。只需相应地设置您的源目录,其余的应该根据您提供的详细信息和我的理解来工作。

我使用了一个简单的批处理 FOR/F 循环,将 MD 与 IF 条件相结合。我使用下限字符作为分隔符,并将标记设置为 5 以完成这项工作。

@ECHO ON
SET Src=C:FolderPath
FOR /F "TOKENS=5 DELIMS=_" %%F IN ('DIR /B /A-D "%Src%*.txt"') DO (
    IF NOT EXIST "%Src%%%~F-P%%~F" MD "%Src%%%~F-P%%~F"
    IF EXIST "%Src%*%%~F*P%%~F*.txt" MOVE /Y "%Src%*%%~F*P%%~F*.txt" "%Src%%%~F-P%%~F"
)
GOTO EOF

更多资源

  • 对于/F
  • 如果
  • 医学博士
  • FOR /?

    delims=xxx      - specifies a delimiter set.  This replaces the
                      default delimiter set of space and tab.
    tokens=x,y,m-n  - specifies which tokens from each line are to
                      be passed to the for body for each iteration.
                      This will cause additional variable names to
                      be allocated.  The m-n form is a range,
                      specifying the mth through the nth tokens.  If
                      the last character in the tokens= string is an
                      asterisk, then an additional variable is
                      allocated and receives the remaining text on
                      the line after the last token parsed.
    

我在下面有一些 C# 代码。 第一部分执行以下操作:

  • 获取路径
  • 获取文件名
  • 修改完整路径以获得 __Mas_ 和最后一个 _ 之间的"147852"部分

        string pathToGetFile = @"C:\";
        string[] filePaths = System.IO.Directory.GetFiles(pathToGetFile +@"\", "*_Mas_*");
        string[] fullName = new string[filePaths.Length]; 
        for (int i = 0; i < filePaths.Length; i++)
        {
            fullName[i] = filePaths[i].Substring(filePaths[i].LastIndexOf("\") + 1);
            filePaths[i] = filePaths[i].Substring(filePaths[i].LastIndexOf("_Mas_") + 5);
            int l = filePaths[i].IndexOf("_"); 
            filePaths[i] = filePaths[i].Substring(0, l);
    

现在,您可以使用自己的名称创建文件夹filePaths现在是这样的:147852,P147852

            if (!Directory.Exists(@"C:" + filePaths[i]))
                System.IO.Directory.CreateDirectory(@"C:" + filePaths[i]);
        }

现在只需将文件移动到新目录

        for (int i = 0; i < filePaths.Length; i++)
        {
            string sourceFile = System.IO.Path.Combine(pathToGetFile, fullName[i]);
            string destFile = System.IO.Path.Combine(@"C:" + filePaths[i], @"C:" + filePaths[i] + "\" + fullName[i]);
            File.Copy(sourceFile,destFile,true);
        }

现在,会发生什么

文件:

  • C:\414_gtmlk_videos_Mas_147852_hty1147.xls
  • C:\414_gtmlk_videos_Mas_P147852_hty1147.txt

它们将根据以下内容进行复制:

  • C:\147852\
  • C:\P147852\

最新更新