简体   繁体   中英

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

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? 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. 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?

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.

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. 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). 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. See debugging a batch file why experts in batch file coding run batch files in development from within a command prompt 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. 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 .
  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). 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).

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.

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

See also:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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