BATCH - Find string in text file and add a new string after that line - string

I'm trying to search a text file for a particular string from a bat file. If the string exist, add a new string after it on the next line. I can't seem to get the code below working correctly. Any Ideas?
This is the string i'm searching for in my text file. [/Script/MyGame.Mode]
Here's what the text file looks like.
[/Script/Config.Mode]
Something here 1
Something here 2
[/Script/MyGame.Mode]
Something here 1
Something here 2
[/Script/Edit.Mode]
Something here 1
Something here 2
And here's how I want it to look.
[/Script/Config.Mode]
Something here 1
Something here 2
[/Script/MyGame.Mode]
RedirectReferences=(PackageName="%Package%",PackageURLProtocol="%PackageURLProtocol%",PackageURL="%WebAddress%/%Package%%Ext%",PackageChecksum="")
Something here 1
Something here 2
[/Script/Edit.Mode]
Something here 1
Something here 2
Here's the code I have so far.
#echo off
:GETINFO
echo.
echo.
cls
echo.
echo Let's get some information for your config.
echo Note: The information you enter below is case sensitive. You can copy and paste.
echo.
echo Here's a Package Name example: "DM-MyTest-WindowsNoEditor"
echo.
set /p Package=Enter Package Name:
echo.
echo.
echo.
echo The Package URL Protocol will be "http" or "https"
echo.
set /p PackageURLProtocol=Enter Package URL Protocol:
echo.
echo.
echo.
echo Here's a WebAddress example: "www.myredirect.com/test" (Don't add the trailing /)
set /p WebAddress=Enter Redirect(WebAddress)URL:
echo.
echo.
echo.
echo The file extention is usually ".pak"
echo.
set /p Ext=Enter Map File Extention:
echo.
cls
echo.
echo Please wait... Currently Creating Test References.
:SHOWLINE
echo.
set NewURL=RedirectReferences=(PackageName="%Package%",PackageURLProtocol="%PackageURLProtocol%",PackageURL="%WebAddress%/%Package%%Ext%",PackageChecksum=""^^)
pause
:WRITENEW
set inputfile=game.txt
set outputfile=game.temp.txt
(for /f usebackq^ delims^=^ eol^= %%a in ("%inputfile%") do (
if "%%~a"=="[/Script/MyGame.Mode]" call echo %NewURL%
echo %%a
))>>"%outputfile%"
echo.
pause

When I run the posted code in Command Prompt console I see a syntax error:
) was unexpected at this time.
Apparently the parentheses inside NewURL break things when expanded in the loop.
A straightforward solution would be to delay the expansion by using the call trick:
call echo %%NewURL%%
Alternatively:
setlocal enableDelayedExpansion & echo !NewURL! & endlocal
Or double-escape the closing parenthesis with ^^ (one time for set and another for an expanded value inside the loop):
set NewURL=.............PackageChecksum=""^^)
Another issue is that the output file name is the same as the input file name but it's impossible to redirect output into the same file as you're reading.
Change the output name to a different file. Then replace the original after the loop is finished:
set inputfile=game.txt
set outputfile=game.temp.txt
...................
))>>"%outputfile%"
move/y "%outputfile%" "%inputfile%"
And to change the order of the new string to print it after the found line simply swap the two lines inside the inner loop:
echo %%a
if "%%~a"=="[/Script/MyGame.Mode]" call echo %%NewURL%%

Related

joining lines while adding white-spaces to select strings in CMD is not working

my test string is:
this is a sentence.
google.com
here is another sentence.
microsoft.com
this sentence has no period
my code is:
#echo off
setlocal EnableDelayedExpansion
set row=
#((For /F "EOL=|Delims=" %%# In ('^""%__AppDir__%find.exe" "."^<"%UserProfile%\i.txt"^"')Do #Set /P "=%%# "<NUL)&Echo()>"%UserProfile%\o.txt"
echo %row% >%userprofile%\o.txt
echo %row%
C:\Users\qwerp>joint3
ECHO is off.
i was expecting to get:
google.com microsoft.com
instead i got:
ECHO is off.
what am i doing wrong?
Given your example file content change and the stated intention, this may be sufficient for your needs, simply changing find.exe to findstr.exe, (with appropriate options):
#((For /F "EOL=|Delims=" %%# In ('^""%__AppDir__%findstr.exe" "\." "%UserProfile%\i.txt"^|"%__AppDir__%findstr.exe" "[^\.]$"^"')Do #Set /P "=%%# "<NUL)&Echo()>"%UserProfile%\o.txt"

Replace %%20 in string using windows batch script

I have a use case where I want to replace %%20 which is part of a string for example: "Calculation%%20One". I want to replace this with "Calculation One".
This where I am stuck:
#echo off
setlocal enableextensions disabledelayedexpansion
>"temp" (
echo !Option1!
echo !Option2!
echo !Option3!
)
set "pattern=%%20"
for /f "usebackq delims=" %%a in ("temp") do (
echo data: %%a
set "line=%%a"
setlocal enabledelayedexpansion
if "!line:%pattern%=!"=="!line!" (
set string=!Option1!
set string2=%!string1!:%%20= %
) else (
set string2=%%a
)
endlocal
)
del /q tempFile
Can someone please help me with this? I have a program which is a combination of batch and python.
Thanks
It is unclear for me why the options are written into a temporary file for processing the values of the environment variables Option1, Option2 and Option3. And it would have been good to see the lines which define the environment variables Option1, Option2 and Option3 for the real values assigned to them.
So I suggest here a batch file which replaces %20 as found for example in HTML files or emails by a space character in all Option environment variables.
#echo off
setlocal EnableExtensions DisableDelayedExpansion
set "Option1=Calculation%%20One"
set "Option2=Calculation %%%%20Two!"
set "Option3=Any other string"
cls
echo The options before processing:
echo/
set Option
for /F "delims==" %%I in ('set Option 2^>nul') do call :ProcessOption "%%I"
echo/
echo The options after processing:
echo/
set Option
echo/
endlocal
pause
goto :EOF
:ProcessOption
setlocal EnableDelayedExpansion
set "ModifiedOption=!%~1:%%20= !"
endlocal & set "%~1=%ModifiedOption%"
goto :EOF
It is necessary to use delayed expansion on replacing all occurrences of %20 by a space character because otherwise Windows command interpreter would not know where the environment variable reference with string substitution ends. Replacing a string with percent sign is not possible using immediate expansion for that reason.
The command set Option outputs alphabetically sorted all environment variables starting case-insensitive with the string Option in format variable=value as it can be seen twice on running this batch file.
FOR executes this command with using a separate command process started in background and captures all lines written by command SET to handle STDOUT.
The string 2^>nul is executed finally as 2>nul and redirects the error message output by command SET to handle STDERR to the device NUL to suppress it. SET would output an error message in case of no environment variable starting with Option is defined in current environment. This error condition does not occur with this batch file. Read the Microsoft article about Using Command Redirection Operators. The redirection operator > must be escaped here with ^ to be interpreted first as literal character when Windows command interpreter processes the entire FOR command line before executing the command FOR which executes cmd.exe /c set Option 2>nul in background.
FOR processes the captured output of set Option line by line and splits each line up into substrings (tokens) with using the equal sign as delimiter as specified with delims==. The string left to first equal sign on each line is assigned to loop variable I. This is the name of the environment variable, i.e. Option1, Option2 and Option3 for this batch file.
With each OptionX environment variable name the subroutine ProcessOption is called for replacing all %20 in its value by a space character.
Here is a solution for environment variables with one or more exclamation marks in variable name.
#echo off
setlocal EnableExtensions DisableDelayedExpansion
set "!Option1!=Calculation%%%%20One"
set "!Option2!=City%%20Country"
set "!Option3!=State%%%%20Country"
set "!Option4!=Any other address/string"
cls
echo The options before processing:
echo/
set !Option
for /F "delims==" %%I in ('set !Option 2^>nul') do call :ProcessOption "%%I"
echo/
echo The options after processing:
echo/
set !Option
echo/
endlocal
pause
goto :EOF
:ProcessOption
call set "ModifiedOption=%%%~1%%"
setlocal EnableDelayedExpansion
set "ModifiedOption=!ModifiedOption:%%%%20= !"
set "ModifiedOption=!ModifiedOption:%%20= !"
endlocal & set "ModifiedOption=%ModifiedOption%"
set "%~1=%ModifiedOption%"
set "ModifiedOption="
goto :EOF
This batch code replaces %20 AND %%20 in all environment variables starting with !Option in name by a space character in comparison to above replacing just %20 by a space in environment variables beginning with Option in name.
It is of course a bad idea to use characters in variable names which have a special meaning for Windows command interpreter like the characters &()[]{}^=;!'+,`~|<>%. It is possible as demonstrated above, but it is definitely not a good idea.
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 /?
echo /?
endlocal /?
for /?
goto /?
set /?
setlocal /?
See also answer on Single line with multiple commands using Windows batch file for an explanation of & operator.
And read DosTips forum topic ECHO. FAILS to give text or blank line - Instead use ECHO/ why it is better to use echo/ instead of echo. to output an empty line.

Get base name of file without file extension

Let's say I'd have a file named "testfile.txt" set on a variable:%File% and I'd like to remove the extension when echoing it . Echo %File:~0,8% would come out as "testfile" but what I want to do is to have it display anything and everything to the left of the ".txt" because I won't always make files which have 8 characters in their name.
Is there a simple solution to this ?
Yep.
for %%I in ("testfile.txt") do echo %%~nI
or
for %%I in ("%file%") do echo %%~nI
Do help for in a cmd console window and see the last two pages for more information on tilde operations.
There is another way to accomplish what you want, using substring substitution similar to your attempts illustrated in your question.
set "file=testfile.txt"
echo %file:.=&rem;%
That substitutes the dot with &rem;. When the variable is evaluated, the batch interpreter treats the newly substituted data as a compound command. And since everything following rem is treated as a remark to be ignored, you're left with only testfile as the output. This will only work if:
you don't include quotation marks in your variable value
your filename only includes the one dot
you don't do it within a parenthetical code block (if statement or for loop) where delayed expansion is required
You can try this:
#echo off
set "file=testfile.txt"
call :removeExtension "%file%"
echo %newFile%
pause
goto :eof
:removeExtension
set "newFile=%~n1"
goto :eof
However, this only works if the file has no path. If it does, you can do this:
#echo off
setlocal EnableDelayedExpansion
set "file=files\testfile.txt"
call :removeExtension "%file%"
echo %newFile%
pause
goto :eof
:removeExtension
set "file=%~1"
set "newFile=!file:%~x1=!"
goto :eof

Find a string and replace specific letters in batch file

I have a to create an autosys job to trigger a batch file which would find a specific string and then replace the next 4 characters.
For example if file (with multiple lines) has below content and i am searching for played
the mad fox jumped of the old vine and
played soccer.
I should replace "socc" with "INFA"
I am new to batch files and my lead has been insisting that i do this using a batch file only. Any help would be greatly apprciated.
Thanks,
Joy
#echo off &setlocal
set "search=search string"
set "replace=kordo anstataui"
set "textfile=file.txt"
set "newfile=new.txt"
(for /f "delims=" %%i in ('findstr /n "^" "%textfile%"') do (
set "line=%%i"
setlocal enabledelayedexpansion
set "line=!line:%search%=%replace%!"
echo(!line!
endlocal
))>"%newfile%"
type "%newfile%"
Apparently you are searching for "played " with a space at the end, although your question is a bit vague.
See my hybrid JScript/batch utility called REPL.BAT that does regular expression search and replace. It works on any modern version of Windows from XP onward, and it does not require installation of any 3rd party executeables.
Using REPL.BAT:
type "yourFile.txt"|repl "played ...." "played INFA" >"yourFile.txt.new"
move /y "yourFile.txt.new" "yourFile.txt" >nul
I use this at times: sar.bat
::Search and replace
#echo off
if "%~3"=="" (
echo.Search and replace
echo Syntax:
echo "%~nx0" "filein.txt" "fileout.txt" "regex" "replace_text" [first]
echo.
echo.EG: change the first time apple appears on each line, to orange
echo."%~nx0" "my text old.txt" "my text changed.txt" "apple" "orange" first
echo.
echo.People that are familiar with regular expressions can use some:
echo.
echo.Change every line starting from old (and everything after it^) to new
echo."%~nx0" "my text old.txt" "my text changed.txt" "old.*" "new"
echo.
echo.If [first] is present only the first occurrence per line is changed
echo.
echo.To make the search case sensitive change
echo.IgnoreCase= from True to False
echo.
pause
goto :EOF
)
if "%~5"=="" (set global=true) else (set global=false)
set s=regex.replace(wscript.stdin.readall,"%~4")
>_.vbs echo set regex=new regexp
>>_.vbs echo regex.global=%global%
>>_.vbs echo regEx.IgnoreCase=True
>>_.vbs echo regex.pattern="%~3"
>>_.vbs echo wscript.stdOut.write %s%
cscript /nologo _.vbs <"%~1" >"%~2"
del _.vbs
Get yourself a copy of sed for your OS and call it from a batch file.
sed -e 's/socc/INFA/g' inputFileName > outputFileName
#echo off
setlocal EnableDelayedExpansion
set "search=played "
set replacement=INFA
set numChars=4
set line=the mad fox jumped of the old vine and played soccer.
rem The characters after the equal-signs are Ascii-254
for /F "tokens=1* delims=■" %%a in ("!line:%search%=■!") do (
set "rightPart=%%b"
set "line=%%a%search%%replacement%!rightPart:~%numChars%!"
)
echo !line!
Output:
the mad fox jumped of the old vine and played INFAer.
You must insert previous code into a loop that process the entire file. I left that part as an exercise for you...

String processing using Batch Script

I'm currently creating a batch script that has to loop through the lines in a file, checking for some string, and if theres a match prefix that string with a '#' (comment it out).
I'm perfectly new to batch script, all I got this far is:
for /f %%j in (CMakeLists.txt) do (
if "%%j"=="Extensions_AntTweakBar" (
echo lol1
)
if "%%j"=="Extensions_Inspection" (
echo lol2
)
if "%%j"=="Extensions_InspectionBar" (
echo lol3
)
)
So my current issue is, I don't know how to operate on string within batch scripts. If someone could help me out that would be appreciated :)
You can just use the text you want to append followed by your variable generally.
C:\>set MY_VAR=Hello world!
C:\>echo #%MY_VAR%
#Hello world!
C:\>set MY_VAR=#%MY_VAR%
C:\>echo %MY_VAR%
#Hello world!
If you're just doing echo, that's fine. echo #%%j will do what you need.
But if you want to set the line to a variable, you have to enable delayed expansion. Add setlocal ENABLEDELAYEDEXPANSION to the top of your file and then surround your variables with ! instead of %. For example (and notice that I've added delims= to put the entire line in %%j instead of the first word on the line):
#echo off
setlocal ENABLEDELAYEDEXPANSION
set LINE=
for /f "delims=" %%j in (CMakeLists.txt) do (
set LINE=%%j
if "%%j"=="Extensions AntTweakBar" (
set LINE=#%%j
)
if "%%j"=="Extensions Inspection" (
set LINE=#%%j
)
if "%%j"=="Extensions InspectionBar" (
set LINE=#%%j
)
echo !LINE!
)
Given this input file:
Extensions AntTweakBar
some text
Extensions Inspection
Extensions What?
some more text
Extensions InspectionBar
Extensions InspectionBar this line doesn't match because delims= takes all text
even more text
The above script produces this output:
C:\>comment.bat
#Extensions AntTweakBar
some text
#Extensions Inspection
Extensions What?
some more text
#Extensions InspectionBar
Extensions InspectionBar this line doesn't match because delims= takes all text
even more text
And of course removing #echo off will help you debug problems.
But all that being said, you're about at the limit of what you can accomplish with batch string processing. If you still want to use batch commands, you may need to start writing lines to temporary files and using findstr with a regex.
Without a better understanding of what you want inside your loop or what your CMakeLists.txt file looks like, try this on for starters:
FINDSTR "SOMETHING" %%J && ECHO #%%J || ECHO %%J
The && makes the second command (the ECHO) conditional on the first command exiting without an error state, and the || is like a logical OR and it runs when the first one doesn't.
Really, for modifying the internals of a text file you are probably going to be much better off using either sed or awk - win32 binaries can be found in the UnxUtils project.

Resources