简体   繁体   English

用用户输入文本替换文本,多行

[英]replace text with userinput text, multiple lines

I have a bit of code I am writing in a batch file, I already have it set so that you drag and drop the text onto the batch file and it adds in a header to the top of the.TXT document using a doctument called "Header.txt" shown below我在批处理文件中编写了一些代码,我已经对其进行了设置,以便您将文本拖放到批处理文件中,并使用名为“ Header.txt”如下图

Date: _DATE_
Time: _TIME_
Job ID: _ID_
Plant: _PLANT_
Code: _CODE_
Program: _PROGRAM_
Hand: _HAND_
Group: _GROUP_

LABEL                                 X-POS      Y-POS       Z-POS     X-CHK      Y-CHK     Z-CHK                                           I         J          K         +TOL       -TOL
===========================================================================================================================================================================================

how do I go about replacing text within the document?我如何 go 关于替换文档中的文本? sofar below is my attempt:以下是我的尝试:

@if not "%~1" == "" copy /B "C:\Users\dougj\Desktop\New folder\HEADER.TXT"+"%~1" "%~1.tmp" >nul & move /Y "%~1.tmp" "%~1"
GOTO  :USERINPUT
CLS

:USERINPUT
COLOR 7C 

    
    SET /p _INPUTNAME= Please Input DATE:
    
    
    FOR /F "delims=" %%G IN (
        'FORFILES /P "%~1" /C "cmd /c echo @path"'
    ) DO (
    for /f "delims=" %%H in ('type "%%~G" ^& break ^> "%%~G" ') do (
        set "line=%%H"
        setlocal enabledelayedexpansion
        >>"%%~G" echo(!line:_DATE_=%_INPUTNAME%
        endlocal
)
)
pause
cls


GOTO :Finish

:Finish
CLS
COLOR E3
Echo.
Echo.
ECHO              FINISHED!
Echo       Press any key to exit...
Echo.
Echo.

Pause
CLS
EXIT

I ran the code and it gives me an ERROR: "The specified directory does not exist.我运行了代码,它给了我一个错误:“指定的目录不存在。

The Windows command processor cmd.exe is designed for running commands and executables. Windows 命令处理器cmd.exe专为运行命令和可执行文件而设计。 It is not designed for a modification of a text file like doing a search and replace for something in a text file.它不是为修改文本文件而设计的,例如搜索和替换文本文件中的某些内容。
See How can you find and replace text in a file using the Windows command-line environment?请参阅如何使用 Windows 命令行环境查找和替换文件中的文本?

For this task with known header content it is easier to create the header file with the user input date manually, next copy the just created header file and the specified file(s) together to temporary file(s) and replace the original file(s) with the temporary file(s) with header inserted at top, and finally delete the created header file.对于已知 header 内容的任务,使用用户手动输入日期更容易创建 header 文件,然后复制刚刚创建的 header 文件和临时文件一起替换原始文件(() ) 在顶部插入带有 header 的临时文件,最后删除创建的 header 文件。

Batch file code for this task:此任务的批处理文件代码:

@echo off
setlocal EnableExtensions DisableDelayedExpansion
set "AutomaticClose="
setlocal EnableDelayedExpansion
for %%I in (!CMDCMDLINE!) do if /I "%%~I" == "/C" endlocal & set "AutomaticClose=1" & goto CheckArguments
endlocal

:CheckArguments
if "%~1" == "" goto ShowUsageHelp
if "%~1" == "/?" goto ShowUsageHelp
set "TempHeaderFile=%TEMP%\%~n0.tmp"
color 7C
echo/
for /F "tokens=1-3 delims=/: " %%I in ('%SystemRoot%\System32\robocopy.exe "%SystemDrive%\|" . /NJH') do set "DefaultDate=%%I-%%J-%%K" & goto UserPromptDate

:UserPromptDate
set "InputDate=%DefaultDate%"
set /P "InputDate=Please input date (default: %InputDate%): "
rem Remove all double quotes from input string.
set "InputDate=%InputDate:"=%"
rem Has the user not input anything else than double quotes?
if not defined InputDate goto UserPromptDate
color

setlocal EnableDelayedExpansion
(
echo Date: !InputDate!
echo Time: _TIME_
echo Job ID: _JOBID_
echo Plant: _PLANT_
echo Code: _CODE_
echo Program: _PROGRAM_
echo Hand: _HAND_
echo Group: _GROUP_
echo/
echo LABEL                     X-POS  Y-POS      Z-POS     X-CHK       Y-CHK      Z-CHK                                           I         J         K          +TOL      -TOL
echo ===========================================================================================================================================================================================
)>"%TempHeaderFile%"
endlocal

for %%I in (%*) do (
    copy /B "%TempHeaderFile%"+"%%~I" "%%~I.tmp" >nul
    if exist "%%~I.tmp" move /Y "%%~I.tmp" "%%~I"
    if exist "%%~I.tmp" del "%%~I.tmp"
)
del "%TempHeaderFile%"

if defined AutomaticClose cls & color E3
echo/
echo/
echo              FINISHED!
if defined AutomaticClose echo       Press any key to exit...
echo/
if defined AutomaticClose pause >nul & color
goto EndBatch

:ShowUsageHelp
if defined AutomaticClose color 7C
echo/
echo Usage: %~n0 "[PATH\]Document File Name 1" ["[PATH\]Document File Name 2"] ...
echo/
if defined AutomaticClose pause

:EndBatch
endlocal

This batch file has some additional enhancements:这个批处理文件有一些额外的增强:

  1. It finds out by processing the value of the environment variable CMDCMDLINE if Windows command processor cmd.exe was started with option /C or /c to automatically close after execution of the batch file.它通过处理环境变量CMDCMDLINE的值来确定 Windows 命令处理器cmd.exe是否使用选项/C/c启动以在执行批处理文件后自动关闭。 In this case the environment variable AutomaticClose is defined which results in using additional commands for users running the batch file with a double click from Windows shell (desktop, start menu, taskbar) or Windows File Explorer (or any other file manager) without or with dragging and dropping one or more files on the batch file (or a shortcut running the batch file).在这种情况下,环境变量AutomaticClose被定义,这将导致用户通过双击 Windows shell(桌面、开始菜单、任务栏)或 ZAEA23489CE3AA9B6406EBB28E0CDA 或 ZAEA23489CE3AA9B6406EBB28E0CDA4 运行批处理文件的用户使用附加命令在批处理文件(或运行批处理文件的快捷方式)上拖放一个或多个文件。 Otherwise the batch file is started from within a command prompt window or with option /K or /k to keep the command process running after finishing processing of the batch file.否则,批处理文件从命令提示符 window 或使用选项/K/k启动,以在完成批处理文件处理后保持命令进程运行。 See debugging a batch file why experts in batch file coding run batch files in development from within a command prompt window.请参阅调试批处理文件为什么批处理文件编码专家在命令提示符 window 中运行开发中的批处理文件。
  2. It can process multiple files on being started with multiple file names.它可以在以多个文件名启动时处理多个文件。 It is also possible to run the batch file with a wildcard pattern to process all files matching the wildcard pattern in a folder.还可以使用通配符模式运行批处理文件,以处理文件夹中与通配符模式匹配的所有文件。
  3. It outputs a usage information on being started with no argument (or first argument is just an empty argument string "" ) or with /?它输出一个关于开始时没有参数(或第一个参数只是一个空参数字符串"" )或/?的使用信息。 as first argument.作为第一个论点。
  4. It predefines the environment variable InputDate with current date in international date format yyyy-MM-dd (date format can be changed easily in code) so that the user of the batch file can hit just RETURN or ENTER to use the current date.它以国际日期格式yyyy-MM-dd (日期格式可以在代码中轻松更改)预定义具有当前日期的环境变量InputDate ,以便批处理文件的用户只需按RETURNENTER即可使用当前日期。 For a description of the command line used to get the current date in format yyyy-MM-dd see the answers on Time is set incorrectly after midnight .有关用于以yyyy-MM-dd格式获取当前日期的命令行的描述,请参阅Time is set wrong after午夜后的答案。
  5. It is possible to right click on the batch file, left click in opened context menu in submenu Send to on menu item Desktop (create shortcut) , cut the shortcut file created on Windows desktop with Ctrl+X and paste the shortcut file with Ctrl+V into the folder %APPDATA%\Microsoft\Windows\SendTo (enter this string in the address bar of Windows File Explorer and hit RETURN to open this folder).可以右键单击批处理文件,左键单击子菜单中打开的上下文菜单发送到菜单项桌面(创建快捷方式) ,用Ctrl+X剪切在Windows桌面上创建的快捷方式文件,然后用Ctrl +粘贴快捷方式文件V进入文件夹%APPDATA%\Microsoft\Windows\SendTo (在 Windows 文件资源管理器的地址栏中输入此字符串,然后按RETURN打开此文件夹)。 Then it is possible to select multiple files in Windows File Explorer, right click on one of the selected files to open the context menu and left click in submenu Send to on the name of the shortcut file to insert the same header on all files currently selected in Windows File Explorer on not too many files selected (command line length limitation).然后可以在 Windows 文件资源管理器中对 select 多个文件,右键单击所选文件之一打开上下文菜单,然后在子菜单中单击左键发送到快捷文件的名称以插入相同的 Z099FB995346F031C743ZF6上所有文件在 Windows 文件资源管理器中选择的文件不多(命令行长度限制)。

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.要了解使用的命令及其工作原理,请打开命令提示符window,在其中执行以下命令,并仔细阅读每个命令显示的所有帮助页面。

  • call /?
  • cls /?
  • color /?
  • copy /?
  • del /?
  • echo /?
  • endlocal /?
  • for /?
  • goto /?
  • if /?
  • move /?
  • pause /?
  • rem /?
  • robocopy /?
  • set /?
  • setlocal /?

See also:也可以看看:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM