【问题标题】:Copy file from batch file's directory从批处理文件的目录复制文件
【发布时间】:2013-10-18 15:34:58
【问题描述】:

我只知道编写批处理文件的基本知识。我试图弄清楚如何编写一个,给定它所在的任何目录,将复制同一目录中的文件并将其放在新位置。我知道如何复制文件并移动它,但我不知道如何编写批处理文件以了解其目录然后抓取不同的文件。

我读到 %0 代表文件所在的目录,但是我怎样才能将文件附加到该目录?

我试过了:

copy "%0\Move.txt" "C:\"

也许这很愚蠢,但我是新手。请帮忙?

【问题讨论】:

    标签: windows batch-file command-prompt


    【解决方案1】:

    %0 包含批处理脚本的完整路径和文件名。

    仅使用%~dp0 获取不带批处理脚本文件名的路径。

    copy "%~dp0\Move.txt" "C:\"
    

    当您遇到问题时,使用echo 命令查看变量包含的内容。

    echo %0
    

    来自call /?

    Substitution of batch parameters (%n) has been enhanced.  You can
    now use the following optional syntax:
    
        %~1         - expands %1 removing any surrounding quotes (")
        %~f1        - expands %1 to a fully qualified path name
        %~d1        - expands %1 to a drive letter only
        %~p1        - expands %1 to a path only
        %~n1        - expands %1 to a file name only
        %~x1        - expands %1 to a file extension only
        %~s1        - expanded path contains short names only
        %~a1        - expands %1 to file attributes
        %~t1        - expands %1 to date/time of file
        %~z1        - expands %1 to size of file
        %~$PATH:1   - searches the directories listed in the PATH
                       environment variable and expands %1 to the fully
                       qualified name of the first one found.  If the
                       environment variable name is not defined or the
                       file is not found by the search, then this
                       modifier expands to the empty string
    
    The modifiers can be combined to get compound results:
    
        %~dp1       - expands %1 to a drive letter and path only
        %~nx1       - expands %1 to a file name and extension only
        %~dp$PATH:1 - searches the directories listed in the PATH
                       environment variable for %1 and expands to the
                       drive letter and path of the first one found.
        %~ftza1     - expands %1 to a DIR like output line
    
    In the above examples %1 and PATH can be replaced by other
    valid values.  The %~ syntax is terminated by a valid argument
    number.  The %~ modifiers may not be used with %*
    

    【讨论】:

    • 我很感激。但是,如果我输入 echo %0 它只会返回 %0?
    • @KyleWright %0 代表仅在批处理文件中可用的参数 0。 echo %0 不能直接在命令行上工作。
    【解决方案2】:

    如果您只是想将文件从当前目录复制到新目录,您可以这样做:

    copy "Move.txt" "C:\"
    

    不为文件“Move.txt”添加前缀意味着它在当前目录中。

    【讨论】:

    • 如果批处理脚本是从具有不同工作目录集的命令行运行的,则会出现问题。这就是为什么如果不执行cdpushd,则经常使用%0
    • 啊,我当时误解了这个问题。谢谢
    猜你喜欢
    • 2010-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-12
    • 2016-12-03
    • 1970-01-01
    相关资源
    最近更新 更多