Finding text with a batch file using Notepad++ - text

I need to find text in a file when I open it with Notepad++.
For instance I need to find the text "ABC". However the true text I need are 2 numbers that follow "ABC". So I have a batch file that uses Notepad++ to open a particular file when I double click it. It needs to find ABC and then look at the 2 digits directly following it and populate a variable with them.
Some files might contain ABC12 while others might contain ABC21, etc.
All I have so far is the following:
%echo off
"C:\Program Files (x86)\Notepad++\notepad++.exe" %1
FIND [/I] "ABC"
It opens the file fine, but does not search. Please help!
Thanks!

this is a really nice question! Try this:
#ECHO OFF &SETLOCAL
set "LineNr="
for /f "tokens=1*delims=[]" %%a in ('^<"%~1" find /i /n "%~2"') do if not defined LineNr (
set "LineNr=%%a"
SET "Line=%%b"
)
if not defined LineNr (
set "LineNr=1"
SET "Row=1"
GOTO :launch
)
CALL SET "Right=%~2%%Line:*%~2=%%"
CALL SET "Line=%%Line:%Right%=%%"
FOR /f "delims=:" %%a in ('"(echo("%Line%"&#echo()|findstr /o $"') do SET /a Row=%%a-4
:launch
START /b CMD /c ""%ProgramFiles(x86)%\Notepad++\notepad++.exe" -n%LineNr% -c%Row% "%~1""
calling the batch:
script.bat "D:\PATH\FILE.TXT" "STRING TO SEARCH"
notepad++ command line switches

Related

How to modify lines that hold a given string with new information and save it as a text file

I am working on modifying our batch files where we call #make functions inside. We want to add a script inside the batch file that checks an external header file, finds the line with date information(APP_VERSION_DATE) and updates the information there with new date information(I figured out how to fetch windows date information with batch, this is not an issue)
I know what steps to follow but batch syntax feels completely counter intuitive to me and I am stuck.
These are the steps I would like to follow:
1- Go through the app_version.h file line by line(for /f)
2- Find the lines with string APP_VERSION_DATE(if findstr...)
3- delete everything except APP_VERSION_DATE
4- CONCAT date information to APP_VERSION_DATE like APP_VERSION_DATE "23-05-2022"
5- Keep echoing every other line
6- Pipeline the information a new header file.
7- Delete header file
8- Rename the new header line as the old one.
set strToFind="app_version_date"
set result="Not Found"
for /f "tokens=2 delims=[]" %%A in ('findstr %strToFind% %filename%') do (
set result=%%A
if defined result (
if %result%==this is something
echo hurra this is it
) ELSE echo
)
this is where I am at right now and I am obviously still too far off to do something I want to do.
I am able to make a program that can find a given string in a file and change it but in this case I want to find the line that has the string I am searching for, delete the rest and modify it. I want to find the line where the string is and modify it, not the string itself. This is simply because date information as shown below;
#define APP_VERSION_DATE [2022-05-16 12:13]
won't be static and ever changing with each compile attempt.
I have something like this but this is too far from what I want to do.
Any help would be great! Thanks in advance
Replace date/time in header file app_version.h
There could be used the following commented batch file for this task:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
set "HeaderFile=app_version.h"
if not exist "%HeaderFile%" exit /B 20
rem Get current local date/time in format [yyyy-MM-dd HH:mm].
for /F "tokens=1-5 delims=/: " %%G in ('%SystemRoot%\System32\robocopy.exe "%SystemDrive%\|" . /NJH') do set "AppVersionDate=[%%G-%%H-%%I %%J:%%K]" & goto UpdateHeaderFile
rem Let FINDSTR output all lines of the header file with a line number and
rem a colon at the beginning for processing really all lines including the
rem empty lines in the header file and output all lines without the line
rem number and the colon with exception of the line containing the string
rem #define APP_VERSION_DATE which is ignored and instead is output a line
rem defined here with the local date/time determined before. All lines output
rem by the loop are written into a newly created temporary header file.
:UpdateHeaderFile
(for /F delims^=^ eol^= %%I in ('%SystemRoot%\System32\findstr.exe /N "^" "%HeaderFile%" 2^>nul') do (
set "Line=%%I"
setlocal EnableDelayedExpansion
if "!Line:#define APP_VERSION_DATE=!" == "!Line!" (
echo(!Line:*:=!
) else (
echo #define APP_VERSION_DATE %AppVersionDate%
)
endlocal
))>"%HeaderFile%.tmp"
rem Replace the original header file with the temporary header file.
if exist "%HeaderFile%.tmp" move /Y "%HeaderFile%.tmp" "%HeaderFile%" >nul
rem Delete the temporary header file if the command line above failed
rem because of the original header file is read-only or write-protected
rem or currently opened by an application with shared access denied.
if exist "%HeaderFile%.tmp" del "%HeaderFile%.tmp"
endlocal
The environment variable HeaderFile can be defined with an absolute path or a relative path.
Please read the chapter Usage of ROBOCOPY to get current date/time in my answer on Time is set incorrectly after midnight for an explanation of the first for /F command line.
Please read next my answer on How to read and print contents of text file line by line? It describes in full details the second for /F loop with the small modification of an additional IF condition to replace the line containing the string #define APP_VERSION_DATE with an current date/time.
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.
del /?
echo /?
endlocal /?
exit /?
findstr /?
goto /?
if /?
move /?
rem /?
set /?
setlocal /?
See also single line with multiple commands using Windows batch file for an explanation of the unconditional command operator &.
Create header file current_date_time.h with date/time
The task could be done much easier if the file app_version.h contains anywhere the line:
#include "current_date_time.h"
The batch file could be in this case just:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
for /F "tokens=1-5 delims=/: " %%G in ('%SystemRoot%\System32\robocopy.exe "%SystemDrive%\|" . /NJH') do echo #define APP_VERSION_DATE [%%G-%%H-%%I %%J:%%K]>"current_date_time.h"& goto EndBatch
:EndBatch
endlocal
This batch file always creates new the file current_date_time.h with just the single line:
#define APP_VERSION_DATE [2022-05-23 18:48]
And this single preprocessor macro definition line is included on compilation into app_version.h.
Define preprocessor macro APP_VERSION_DATE with current date/time
Every C/C++ compiler has an option to define a preprocessor macro on the command line and the option can be used multiple times on the command line to define multiple preprocessor macros.
For example see:
GNU gcc/g++: Options Controlling the Preprocessor explaining case-sensitive option -D
Microsoft C/C++: /D (Preprocessor Definitions)
So it is possible to define an environment variable with the current date/time in the wanted format with the single command line below and reference this environment variable value on running the C/C++ compiler with the appropriate option.
#set "AppVersionDate=" & for /F "tokens=1-5 delims=/: " %%G in ('%SystemRoot%\System32\robocopy.exe "%SystemDrive%\|" . /NJH') do #if not defined AppVersionDate set "AppVersionDate=[%%G-%%H-%%I %%J:%%K]"
GNU gcc/g++ would be run later with -D "APP_VERSION_DATE=%AppVersionDate%" and Microsoft C/C++ compiler with /D "APP_VERSION_DATE=%AppVersionDate%" as one of the options on compilation of the C/C++ source code files.
There are also the predefined macros __DATE__ and __TIME__:
GNU gcc/g++: Predefined Macros
Microsoft C/C++: Predefined macros
Search also for information about the environment variable SOURCE_DATE_EPOCH which gives control over the timestamp added by the C/C++ compiler itself to the produced binaries.

Batch Move based on filename without Delimiters, String Only

Okay, Windows 7 Enterprise x64 here with a Windows batch file question. I am a somewhat basic user with little knowledge of batch file creation. I've modified existing scripts I've found online to my use, that is about it.
I have a piece of software that dumps it's output to a folder with file names concatenated from the project title, current system date, current system time, and project settings.
It will export two files in this format every time the project is saved:
PROJECTTITLE_2016_10_07__09_45_11__A_B_C.iges
PROJECTTITLE_2016_10_07__09_45_11__A_B_C.step
The A, B, and C representing switches used in the software that are specific to the project. These may exist or may not exist as in the file name can be _R_F or _R_F_Z etc.
"PROJECTTITLE" can literally be anything. This is where my problem arises using delimiters. You could potentially have file names like all of the following (using real examples from users):
11475shacklebody_2016_10_07__09_45_11__R_F.iges
11475shacklebody_2016_10_07__09_45_11__R_F.step
test_EFMflow_2016_10_07__09_45_11__R_Z.iges
test_EFMflow_2016_10_07__09_45_11__R_Z.step
untitled16_2016_10_07__09_45_11__R.iges
untitled16_2016_10_07__09_45_11__R.step
#14drop_wire-edm_2016_10_07__09_45_11__R_F_Z.iges
#14drop_wire-edm_2016_10_07__09_45_11__R_F_Z.step
prooftestwithoutupperlandsimproved-4_2016_10_07__09_45_11.iges
prooftestwithoutupperlandsimproved-4_2016_10_07__09_45_11.step
What I want to do is move both the IGES and STEP files from the output folder on the C drive to a new folder on a networked drive with name based on "PROJECTTITLE," creating that folder if needed. I have already task scheduled a -delim based batch to run every night, but found delimiters to not be sufficient for my use.
While it seems like an easy job to do with delimiters, looking for the first underscore, I have had projects with underscores in their names that screws up the folder naming. Since delimiters only work for individual characters, not strings, I have been looking for examples of batch files I can adapt to my use with no luck finding any similar to what I want to do that do not use delimiters.
It seems simple, search for string "_2016," in filename, and take all characters before "_2016" and create a new directory, placing files containing those characters in that folder. I am lost as to how to do this without delimiters though.
What I have working so far, using delimiters looking for underscores, creating folders and moving to those folders on a mapped drive:
for /f "delims=_" %%V in ('dir /b /a-d C:\Output\*_*.iges') do (
mkdir "I:\ENG\PARTS\%%V" 2>nul
move "C:\Output\%%V_*.iges" "I:\ENG\PARTS\%%V" >NUL 2>nul
move "C:\Output\%%V_*.step" "I:\ENG\PARTS\%%V" >NUL 2>nul
)
It is a very simple batch file for what it does, but falls flat on it's face with titles containing underscores.
A few things:
Searching for _2016 would mean the batch file would need yearly maintenance. Could we either search for system %YEAR% or somehow search for "_####_##_##_" with something like a regular expression to get away from searching for system date or a specific year?
EDIT:
While not ideal as the switches are useful, I found a way in the software to not export the project specific switches at the end of the file name. So now the export would be:
PROJECTTITLE_2016_10_07__09_45_11.iges
PROJECTTITLE_2016_10_07__09_45_11.step
Which I know I can trim from right, what, 21 characters, use that name to make a folder and search the directory for all files containing that trimmed string.
It still would be nice to figure out how to search for the specific string though with the switches intact. I am willing to learn, so throw all explanations of your code you can at me.
Double (Late) EDIT:
First, thank you all for answering this, I deeply appreciate your help.
Double underscores in the the filename are quite rare, but do happen, probably due to typos. It becomes more of an issue with the volume of files I'm planning to move with this. The software runs on maybe 100 user machines with 20 or so being heavy users, each saving up to maybe 1000 files a day. The software will automatically save in increments, as the user runs the simulation. I'm trying to give them a way to collaborate and view each other's simulation results over the network (that we actively encourage them to use) and it figures that the software is hard coded to output to the C drive (for "performance" as the vendor tells me). I'm looking into scheduling the files to move every 15 minutes on every PC in their OU instead of nightly to give a near-real-time view on what they are working on.
Another option I explored was symbolically linking the output folder on each machine to the software's folder network drive, but found that this really doesn't solve the user's "organization" issue, putting like project runs in the same folder. This also has the issue of not allowing them to save a project out of the office without VPN, which some users do do, then move their files over when they get back in the office.
Thank you for your assistance.
Next batch script should do the job even if a file name contains cmd poisonous characters like space or % percent sign etc.
#ECHO OFF
SETLOCAL EnableExtensions DisableDelayedExpansion
set "_fouts=C:\Output" your setting
set "_fouts=D:\test\39924063" my setting
for /F %%G in ('wmic OS get localdatetime ^|find "."') do set "_fyear=%%G"
pushd "%_fouts%"
set "_fyear=%_fyear:~0,4%"
call :doDir
set /A _fyear -= 1
call :doDir
popd
ENDLOCAL
goto :eof
:doDir
rem debugging output echo(%_fyear%
for /f "delims=" %%V in ('
dir /b /a-d "*_%_fyear%_*.iges" "*_%_fyear%_*.step" 2^>NUL') do (
set "_fname=%%~nV" filename without extesion
set "_fexte=%%~xV" extesion only
call :doAll
)
goto :eof
:doAll
call set "_ftail=%%_fname:*_%_fyear%_=%%"
call set "_fproj=%%_fname:_%_fyear%_%_ftail%=%%"
rem debugging output echo("%_fproj%" "%_fname%" "%_fexte%"
ECHO mkdir "I:\ENG\PARTS\%_fproj%" 2>nul
ECHO move "%_fname%%_fexte%" "I:\ENG\PARTS\%_fproj%\"
goto :eof
Output (note that operational mkdir and move commands are merely displayed for debugging purposes using ECHO mkdir and ECHO move, respectively):
==> dir /B /S "D:\test\39924063" /S
D:\test\39924063\#14drop_wire-edm_2016_10_07__09_45_11__R_F_Z.iges
D:\test\39924063\#14drop_wire-edm_2016_10_07__09_45_11__R_F_Z.step
D:\test\39924063\%PROJECT TITLE_2016_10_07__09_45_11__A_B_C.iges
D:\test\39924063\%PROJECT TITLE_2016_10_07__09_45_11__A_B_C.step
==> D:\bat\SO\39924063.bat
mkdir "I:\ENG\PARTS\#14drop_wire-edm"
move "#14drop_wire-edm_2016_10_07__09_45_11__R_F_Z.iges" "I:\ENG\PARTS\#14drop_wire-edm\"
mkdir "I:\ENG\PARTS\%PROJECT TITLE"
move "%PROJECT TITLE_2016_10_07__09_45_11__A_B_C.iges" "I:\ENG\PARTS\%PROJECT TITLE\"
mkdir "I:\ENG\PARTS\#14drop_wire-edm"
move "#14drop_wire-edm_2016_10_07__09_45_11__R_F_Z.step" "I:\ENG\PARTS\#14drop_wire-edm\"
mkdir "I:\ENG\PARTS\%PROJECT TITLE"
move "%PROJECT TITLE_2016_10_07__09_45_11__A_B_C.step" "I:\ENG\PARTS\%PROJECT TITLE\"
==>
Resources (required reading, incomplete):
(command reference) An A-Z Index of the Windows CMD command line
(additional particularities) Windows CMD Shell Command Line Syntax
(%~nV, %~xV etc. special page) Command Line arguments (Parameters)
(set "_fyear=%_fyear:~0,4%" etc.) Extract part of a variable (substring)
(%variable:StrToFind=NewStr% etc.) Variable Edit/Replace
#ECHO OFF
SETLOCAL
SET "sourcedir=U:\sourcedir"
SET "destdir=U:\destdir"
REM (
FOR /f "delims=" %%a IN (
'dir /b /a-d "%sourcedir%\*__*" '
) DO (
IF /i "%%~xa"==".iges" CALL :process "%%a"
IF /i "%%~xa"==".step" CALL :process "%%a"
)
REM )>"%outfile%"
GOTO :EOF
:: Process filename "%1"
:process
SET "fullname=%~1"
SET "junk=%fullname:*__=%"
CALL SET "project=%%fullname:%junk%=%%"
SET "project=%project:~0,-13%
ECHO(MD "%destdir%\%project%"
ECHO(MOVE "%sourcedir%\%~1" "%destdir%\%project%\"
GOTO :eof
You would need to change the settings of sourcedir and destdir to suit your circumstances.
The required MD commands are merely ECHOed for testing purposes. After you've verified that the commands are correct, change ECHO(MD to MD to actually create the directories. Append 2>nul to suppress error messages (eg. when the directory already exists)
The required MOVE commands are merely ECHOed for testing purposes. After you've verified that the commands are correct, change ECHO(MOVE to MOVE to actually move the files. Append >nul to suppress report messages (eg. 1 file moved)
This approach simply performs a directory list without directorynames (/a-d) of each file in the source directory that contains a double-underscore. Each filename matching is assigned to %%a and if the extension part (%%~xa) is one of the targets, then process the filename.
Processing consists of removing all of the characters before the double-underscore and then removing that junk part from the full name, giving project+date. Remove the last 13 characters and you have your project name.
Will have problems with any filename containing certain symbols like % or = but should be fine with underscores.
This version assumes there will not be an instance of _YYYY_ in the PROJECTTITLE.
#Echo Off
SetLocal EnableExtensions DisableDelayedExpansion
(Set OutDir=I:\ENG\PARTS)
(Set SrcDir=C:\Output)
If Not Exist "%SrcDir%\" Exit/B 1
If Not Exist "%OutDir%\" Exit/B 1
For /F "EOL=Y" %%A In ('WMIC Path Win32_LocalTime Get Year') Do (
For /F "Delims=" %%B In ("%%A") Do Set "ThisYr=%%B")
For /F "Delims=" %%A In ('Where "%SrcDir%:*_%ThisYr%_*.iges"') Do (
If Exist "%%~dpnA.step" Call :Sub %%~nA)
Exit/B
:Sub
Set "BigTit=%~1"
For /F "Delims=" %%A In ('CMD /Q /C "Call Echo %%BigTit:_%ThisYr%_=&:%%"') Do (
If Not Exist "%OutDir%\%%A\" MD "%OutDir%\%%A"
Move "%SrcDir%\%~1*.*" "%OutDir%\%%A">Nul)
Edit, there is no need to export without the potentially useful project switches using the above code.
Supposing the PROJECTTITLE part of the file names does not contain two consecutive underscores, you could use the following script, which splits off the first occurrence of __ and everything after (so the time part and the optional switches are removed), using a standard for loop rather than for /F; then it splits off another 11 characters (hence the remaining date part), using sub-string expansion:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
rem // Define constants here:
set "_SOURCE=."
set "_TARGET=."
for /F delims^=^ eol^= %%F in ('
pushd "%_SOURCE%" ^&^& ^(
dir /B /A:-D ^
"*_????_??_??__??_??_??*.iges" ^
"*_????_??_??__??_??_??*.step" ^
^& popd^)
') do (
call :PROCESS "%%F"
)
endlocal
exit /B
:PROCESS val_file
setlocal DisableDelayedExpansion
set "FILE=%~1"
setlocal EnableDelayedExpansion
for %%I in ("!FILE:__=";"!") do (
endlocal
set "ITEM=%%~I"
setlocal EnableDelayedExpansion
goto :NEXT
)
:NEXT
if defined ITEM (
set "ITEM=!ITEM:~,-11!"
md "%_TARGET%\!ITEM!" 2> nul
if not exist "%_TARGET%\!ITEM!\!FILE!" (
move /Y "%_SOURCE%\!FILE!" "%_TARGET%\!ITEM!\" > nul
)
)
endlocal
endlocal
exit /B
Finally I come up with a script that is able to handle even files whose PROJECTTITLE part contain __ on their own. It splits off the last occurrence of __ and everything after (so the optional switches are removed, if any, or the time part is removed otherwise), using a standard for loop rather than for /F; then it splits off another 21 characters (hence the remaining date and time parts), or, if no optional switches were present, just another 11 characters (hence the remaining date part), using sub-string expansion:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
rem // Define constants here:
set "_SOURCE=."
set "_TARGET=."
for /F delims^=^ eol^= %%F in ('
pushd "%_SOURCE%" ^&^& ^(
dir /B /A:-D ^
"*_????_??_??__??_??_??*.iges" ^
"*_????_??_??__??_??_??*.step" ^
^& popd^)
') do (
call :PROCESS "%%F"
)
endlocal
exit /B
:PROCESS val_file
setlocal DisableDelayedExpansion
set "FILE=%~1"
set "BASE=%~n1"
set "NAME=" & set "ITEM="
setlocal EnableDelayedExpansion
for %%I in ("!BASE:__=";"!") do (
for /F "delims=" %%E in ("!NAME!!ITEM!__") do (
endlocal
set "NAME=%%E"
set "ITEM=%%~I"
setlocal EnableDelayedExpansion
)
)
if defined NAME (
set "NAME=!NAME:~2,-2!"
echo("!ITEM!"| > nul findstr /R "^\"[0-9][0-9]_[0-9][0-9]_[0-9][0-9]\"$" || (
if defined NAME set "NAME=!NAME:~,-10!"
)
if defined NAME set "NAME=!NAME:~,-11!"
if defined NAME (
md "%_TARGET%\!NAME!" 2> nul
if not exist "%_TARGET%\!NAME!\!FILE!" (
move /Y "%_SOURCE%\!FILE!" "%_TARGET%\!NAME!\" > nul
)
)
)
endlocal
endlocal
exit /B

Batch file search & create with more than one word

I need your help, I am fairly new at this type of scripting, and I need your help to try and get this script to function correct.
I have a script that searches a folder for files and moves them to a folder name after the files first characters. But I have an issue when the files are seperated by more than one '.'.
setlocal EnableDelayedExpansion
set "IncomingFolder=D:\Test"
set "showsFolder=D:\Test\"
for %%F in ("%incomingFolder%\*.S*.*") do ( for /f "delims=.S" %%A in ("%%~nF") do (
if not exist "%showsFolder\%" md "%showsFolder%\%%A"
move "%%F" "%showsFolder%\%%A" ) )
For example:
If the files is Hustle.SXX.XXX Then it makes the correct folder named "Hustle".
But if it is named The.Hustle.SXXX.XXX then it makes a folder called "The" only, I need it to use the whole name until ".S".
Anybody who can help me with this?
#ECHO OFF
SETLOCAL
set "IncomingFolder=c:\sourcedir"
set "showsFolder=D:\Test"
for %%F in ("%incomingFolder%\*.S*.*") do (for /f "delims=." %%A in ("%%~nF") do (
ECHO md "%showsFolder%\%%A"
ECHO move "%%F" "%showsFolder%\%%A\"
)
)
GOTO :EOF
I've changed the directory names to suit my system.
I could not recreate the problem you describe, but delims=.S would make the delimiters . or S, not .S. That may be what you are seeing.
The required MD commands are merely ECHOed for testing purposes. After you've verified that the commands are correct, change ECHO MD to MD to actually create the directories. Append 2>nul to suppress error messages (eg. when the directory already exists)
Also, the required MOVE commands are merely ECHOed for testing purposes. After you've verified that the commands are correct, change ECHO MOVE to MOVE to actually move the files. Append >nul to suppress report messages (eg. 1 file moved)
You can't use FOR /F to parse from the front because you don't know how many . may appear in the name. I'm assuming you are expecting names like part1.part2.Spart3.part4, but not like part1.part2.Spart3.part4.part5. In other words - you don't want two dots after the .S. If so, then you can safely remove everything after the second to last dot. That is easily done using the ~n modifier twice.
for %%F in ("%incomingFolder%\*.S*.*") do for %%A in ("%%~nF") do (
if not exist "%showsFolder%\%%~nA" md "%showsFolder%\%%~nA"
move "%%F" "%showsFolder%\%%~nA\"
)
(Tickled by Magoo - % missing on "incoming" and ~n required on move-destination)
This uses a helper batch file called repl.bat - download from: https://www.dropbox.com/s/qidqwztmetbvklt/repl.bat
Place repl.bat in the same folder as the batch file or in a folder that is on the path.
Test this to see how it goes:
#echo off
set "IncomingFolder=D:\Test"
set "showsFolder=D:\Test"
for %%F in ("%incomingFolder%\*.S*.*") do (
for /f "delims=" %%A in (' echo "%%~nF"^|repl ".(.*)S\d\d.*" "$1" ') do (
md "%showsFolder%\%%A" 2>nul
move "%%F" "%showsFolder%\%%A"
)
)
setlocal EnableDelayedExpansion
set "IncomingFolder=D:\Test"
set "showsFolder=D:\Test"
for %%F in ("%incomingFolder%\*.S*.*") do (
set "file=%%~nF"
for /F "delims=" %%A in ("!file:*.S=!") do set "folder=!file:.S%%~A=!"
if not exist "%showsFolder%\!folder!" md "%showsFolder%\!folder!"
move "%%F" "%showsFolder%\!folder!"
)
set "file=%%~nF" get the file name, for example: set "file=The.Hustle.SXXX.XXX"
!file:*.S=! is the part after the first ".S", for example XXX.XXX, so
set "folder=!file:.S%%~A=!" is file name without ".SXXX.XXX", for example: "The.Hustle"

Reading multiple text files and replacing a certain type of string in each of them using a batch file

I need to read all the text files from a directory and then replace a certain type of string (that comes in a line having 'volumelabel') with another (replacewith) in each of them. Following is the code snippet:
for /r %%g in (*.txt) do (
set filename=%%~nxg
for /F "tokens=3 delims=<>" %%i in ('findstr "volumelabel" !filename!') do (
set tobereplaced=%%i
)
echo !filename! has !tobereplaced! to be replaced by %replacewith%
for /F "tokens=*" %%a in (!filename!) do (
set str=%%a
set str=!str:!tobereplaced!=%replacewith%!
echo !str!>>new!filename!
)
)
Now the problem I am facing is it prints only tobereplaced (literally) in every line of the new files when
set str=!str:!tobereplaced!=%replacewith%!
echo !str!>>new!filename!
is used and prints tobereplaced=replacewith (values) when
set str=%str:!tobereplaced!=%replacewith%%
echo !str!>>new!filename!
is used. Can someone help me?
The least convoluted solution (in my humble opinion) is to use a subroutine to set str. Going more than one level deep of delayed expansion tends to cause severe brain hurt. Oh, you could probably fix your set str line by doing something like
call call call set str=%%%%str:%%tobereplaced%%=%replacewith%%%%%
...or similar. See what I mean about brain hurt? It's hard to follow the recursion.
So here's my suggestion for a solution. I also fixed another potential problem or two while I was at it. Since you're doing a recursive search for *.txt, I made the for loops able to work with whatever text files they find within subdirectories. I haven't tested this, so let me know if you get any grotesque errors.
#echo off
setlocal enabledelayedexpansion
set replacewith=whatever
for /r %%g in (*.txt) do (
set newfile=%%~dpng.new%%~xg
for /F "tokens=3 delims=<>" %%i in ('findstr "volumelabel" "%%g"') do (
set "tobereplaced=%%i"
echo %%~nxg has !tobereplaced! to be replaced by %replacewith%
rem combining your for loops this way makes the second only fire if the first is true
rem using "findstr /n" in your for loop preserves blank lines
for /F "delims=" %%a in ('findstr /n "^" "%%g"') do (
rem ...but you have to strip off the line numbers
set "str=%%a" && set "str=!str:*:=!"
rem "call :repl" to work around the delayed expansion conundrum
call :repl "!str!" "!tobereplaced!" "%replacewith%" str
echo !str!>>!newfile!
)
)
)
goto :EOF
:repl <line> <find> <replace> <var>
setlocal enabledelayedexpansion
set "line=%~1"
set "line=!line:%~2=%~3!"
set "%4=%line%"
goto :EOF
Caveat: If your text file contains exclamation marks, equal signs or carats, they might not make it into textfile.new.txt.
For what it's worth, if I were in your position, instead of using a batch file I would probably use sed (the binaries should be all you need). You wouldn't even need a script. You could do it as a one liner like this:
for /r %I in (*.txt) do sed -r "s/volumelabel/replacement/ig" "%I" > "%~dpnI.new%~xI"
By the way, see the last couple of pages of help for for an explanation of the %~dpnI sort of notation.

Escaping an equals sign in DOS batch string replacement command

I need to replace some text in a JNLP file using a DOS batch file to tune it for the local machine.
The problem is that the search pattern contains an equals sign which is messing up the string replacement in the batch file.
I want to replace the line,
<j2se version="1.5" initial-heap-size="100M" max-heap-size="100M"/>
with specific settings for the initial and max heap sizes.
For example at the moment I have,
for /f "tokens=* delims=" %%a in (%filePath%agility.jnlp) do (
set str=%%a
set str=!str:initial-heap-size="100M"=initial-heap-size="%min%M"!
echo !str!>>%filePath%new.jnlp)
but the = in the search pattern is being read as part of the replacement command.
How do I escape the equals sign so it is processed as text?
The best solution is to download and install Cygwin or GNUWin32 but, if you're really limited to the standard command processor, it can get a little messy.
This is not the fastest method in the world but it's at least functional. This command file processes each line one character at a time, treating specially the case where you find the stanza you're looking for.
#echo off
set init=50M
set max=75M
setlocal enableextensions enabledelayedexpansion
for /f "tokens=* delims=" %%a in (agility.jnlp) do (
set str1=%%a
call :morph
echo !str2!>>agility_new.jnlp
echo !str2!
)
endlocal
goto :eof
:morph
set str2=
:morph1
if not "x!str1!"=="x" (
if "!str1:~0,18!"=="initial-heap-size=" (
set str2=!str2!initial-heap-size="!init!"
set str1=!str1:~24!
goto :morph1
)
if "!str1:~0,14!"=="max-heap-size=" (
set str2=!str2!max-heap-size="!max!"
set str1=!str1:~20!
goto :morph1
)
set str2=!str2!!str1:~0,1!
set str1=!str1:~1!
goto :morph1
)
goto :eof
With the input file:
<j2se version="1.5" initial-heap-size="100M" max-heap-size="100M"/>
next line
===
you end up with:
<j2se version="1.5" initial-heap-size="50M" max-heap-size="75M"/>
next line
===
One cannot simply replace (a substring with) an equal-sign, without splitting up (for-statement with "delims==") or trimming…
But perhaps you could go for this simpler but more confusing approach, using the following statement in your for-loop:
set str=!str:"100M" max-heap-size="%min%M" max-heap-size!
It just combines the string to replace with what comes after instead of what comes before, avoiding any equal-sign replacements entirely.
If you can pass the arguments as something else, such as double underscores, you can iterate through them and convert them to '=' in the batch file.
#rem Replace __ with = in batch files.
#rem This works around the lack of equals signs in args
#rem args contains full args string with substitutions in place
setlocal enabledelayedexpansion
:argloop
if "%~1" NEQ "" (
set str=%~1
set out=!str:__==!
set %~1=!out!
set args=!args!!out!
SHIFT
goto :argloop
)
#rem Can now run program on a line on its own with just %args%
Source: https://github.com/mlabbe/batchargs
Here's an alternative solution. If you can afford to download GNU tools, you can use sed:
C:\test>set a=200
C:\test>sed -i.bak "s/^\(.*initial-heap-size=\"\).*\( max.*\)/\1%a%\"\2/" file

Resources