How do i capture a variable from a text file with a batch script? - string

Hi I'm trying to write a batch script that reads a long text file, finds a line that says:
Location: xxxxxxxx
And saves xxxxxxxx (only) as a variable that i can use later in the script.
xxxxxxxx is an ID and there is nothing else on that line.
Can someone help?

This works, too.
for /f "tokens=2" %a in ('type longtextfile.txt ^|findstr /b "Location"') do set location=%a
echo %location%
EDIT: Adding Aacini's more efficient way of doing this:
for /f "tokens=2" %a in ('findstr /b "Location" longtextfile.txt') do set location=%a
echo %location%

There are just a few standard Windows commands required for this simple task:
#echo off
set "TextFile=C:\Temp\Text file to search for location.txt"
if not exist "%TextFile%" echo Can't find file: "%TextFile%"& goto :EOF
for /F "usebackq tokens=1* delims=: " %%I in ("%TextFile%") do (
if /I "%%I" == "Location" (
set "Location=%%J"
goto FoundLocation
)
)
echo No location found in file: "%TextFile%"
goto :EOF
:FoundLocation
echo Location is: %Location%
On second line the name of the text file with path must be defined.
To understand the commands used and how they work, open a command prompt window, execute there the following commands, and read the displayed help pages for each command, entirely and carefully.
echo /?
for /?
if /?
goto /?
set /?

Related

Cannot set environmental variable inside a loop in a batch script

I have a batch script that works great and it does the following:
download EDI files from sftp server
generate a dynamic ftp scripts based on the filenames that were downloaded
uploads the file to an internal ftp server via FTP script
I need to modify the batch file to look at the content as some data coming in maybe missing a 0. I do have the logic on how to do this, however, I cannot add the logic to the loop I have as variables do not work.
Below is loop where I want to add the part to correct missing leading zero (that would be in position 4):
for /F "tokens=*" %%A in (c:\scripts\permitsin.txt) do (
echo put %%A /qsys.lib/MAEPFTDTA.lib/PERMITIN.file/%%A >> c:\scripts\ftp-to-scoopsoft.ftp1
)
What I need to do is add an environment variable which will be the content of the file and below is the sample code:
set /p string =< %%A
echo Value for string is set to %string%
echo %string:~9,1% | find "ECHO is on." > nul
if not errorlevel 1 goto Found0
echo no space found
goto End
:Found0
echo found space
echo below is what the correct number needs to be
echo %string:~0,3%0%string:~3% > %%A
:End
I need this to work in batch file as security requirements does not allow PowerShell on the servers.
for /F "tokens=*" %%A in (c:\scripts\permitsin.txt) do (
for /F "delims=" %%S in (%%A) do (
setlocal enabledelayedexpansion
set "string=%%S"
if "!string:~9,1!"==" " echo !string:~0,3!0!string:~3!> %%A
endlocal
)
echo put %%A /qsys.lib/MAEPFTDTA.lib/PERMITIN.file/%%A >> c:\scripts\ftp-to-scoopsoft.ftp1
)
should do what you appear to need. Test on sample data first, of course.
Here's the how : Stephan's DELAYEDEXPANSION link
And it saves a lot of work if you tell us what you want to do rather than how you want to do it.

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.

Remove Brackets from Variable (CLI-Windows)

Based on the code below, the output of Var is (COM19). I was wandering what command can be used to remove the brackets? Tried using sed, but would ideally want a solution that doesn't not require additional installations on Windows.
#echo off
setlocal
wmic path win32_pnpentity get caption /format:list > output.txt
for /f "tokens=4" %%a in ('find /i "USB Serial Port" output.txt') do set var=%%a
pause
goto :EOF
for /f "delims=()" %%a in ("%output%") do (echo %%a)
Managed to solve the issue ussing the delims, in line with the token function. Code can be seen below.
#echo off
setlocal
wmic path win32_pnpentity get caption /format:list > output.txt
for /f "tokens=2 delims=()" %%a in ('find /i "USB Serial Port" output.txt') do set var=%%a
pause

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"

Do a whois by reading a the domains from a text file

I am trying to do a WHOIS for around 50 domains, i have searched on here and found a script that looks like it works but when i run it, it says:
"The Maximum setlocal recursion has been reached"
"The Process can not access the file, it is being used by another process"
Here is the code.
#echo off
setlocal
for /F "tokens=* EOL=# delims=" %%D in (e:\domains.txt) do call :reportit "%%~D"
endlocal
goto :eof
:reportit
setlocal
set "domain=%~1"
echo " Retrieving details for: %domain%"
echo " WHOIS: %domain%" >> e:\results.txt
echo "=============================================================" >> e:\results.txt
whois %domain% >> e:\results.txt
timeout 8
endlocal
exit /b
Any help will be much appreciated
Don't use WHOIS as the name of your batch.

Resources