根据文件名字符批处理文件来复制文件 [英] Batch file to copy files based on characters in filename

查看:147
本文介绍了根据文件名字符批处理文件来复制文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个批处理文件从一个文件夹复制到多个文件夹,根据文件名复制文件。该文件的形式aBBccccc.txt a和加勒比共同体气候变化没有关系的,但是BB有2个字符codeS。例如文件aQWertyu.txt aWErtyui.txt应该由脚本分别复制到文件夹QW和WE,而这些文件夹将被创建。

I need a batch file to copy files from a single folder to multiple folders, based on filename. The files are of the form aBBccccc.txt where a and ccccc do not matter, but BB are 2 character codes. For example files aQWertyu.txt aWErtyui.txt should be copied to folders QW and WE respectively, and these folders will be created by the script.

我见过使用FOR / F示例脚本,但看不到如何解析文件,检查字符2和3,然后创建该文件夹,复制文件。

I've seen example scripts using the FOR /f, but cannot see how to parse the file, examine characters 2 and 3, then create the folder, and copy the files.

感谢。

推荐答案

这需要多个部分:


  1. 延迟扩展。这需要从下面的循环中获得一个子

  1. Delayed expansion. This is needed to get a substring from within the loop below:

setlocal enableextensions enabledelayedexpansion


  • A 循环用于遍历文件

    for %%x in (*.txt) do (
    


  • 找到相关的字符串:

  • Find the relevant substring:

        set "filename=%%x"
        set "folder=!filename:~1,2!"
    

    请注意使用!文件名!在这里。这是使用延迟扩展。通常,环境变量与%文件名%引用,但这些将被扩展时的解析<​​/ em>的完整的循环那么这将减少%文件名%不了了之。延迟扩展,使用解决这个问题。

    Note the use of !filename! here. This is using delayed expansion. Normally environment variables are referenced with %filename% but those would be expanded when parsing the complete loop which would then reduce %filename% to nothing. Delayed expansion, using ! solves this.

    创建文件夹:

        if not exist !folder! mkdir !folder!
    

    此仅创建,如果它不存在的文件夹。

    This only creates the folder if it doesn't yet exist.

    将文件复制:

        copy "%%x" !folder!
    )
    


  • 全部放在一起:

    @echo off
    setlocal enableextensions enabledelayedexpansion
    for %%x in (*.txt) do (
      set "filename=%%x"
      set "folder=!filename:~1,2!"
      if not exist !folder! mkdir !folder!
      copy "%%x" !folder!
    )
    

    这篇关于根据文件名字符批处理文件来复制文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆