Batch Files: How to concatenate each line in a text file? - batch-file

I have a text file with text on each line. I would like to be able to put each line in one long line along with a space. So, if the text file has:
Bob
Jack
Sam
I want the result to be
Bob Jack Sam
Below are two methods that I am working on but I am stuck. Anything in brackets [] means that I know the syntax is completely wrong; I only put it there to show my thought process. The commented sections are just me experimenting and I have left them in case anyone wants to comment on what they would do / why they do what they do.
Method 1:
#echo off
SETLOCAL EnableDelayedExpansion
SET count=1
FOR /F "tokens=* delims= usebackq" %%x IN ("afile.txt") DO (
SET var!count!=%%x
for %%a in (!count!) do (
!var%%a! = !var%%a! & " "
echo !var%%a!
)
SET /a count=!count!+1
echo !count!
)
::echo !var1! !var2! !var3!
start "" firefox.exe !var%%a!-1
ENDLOCAL
::echo "endlocal" %var1% %var2% %var3%
Method 2:
#echo off
SETLOCAL EnableDelayedExpansion
SET count=1
FOR /F "tokens=* delims= usebackq" %%x IN ("afile.txt") DO (
SET var!count!=%%x
call echo %%var!count!%%
SET /a count=!count!+1
echo !count!
)
::echo !var1! !var2! !var3!
start "" firefox.exe ^
[i = 1]
[for i to !count! do (]
call echo %%var!count!%% & " " & " "^
ENDLOCAL
::echo "endlocal" %var1% %var2% %var3%

If you only have three values, you can directly retrieve them from the file
< input.txt (
set /p "line1="
set /p "line2="
set /p "line3="
)
set "var=%line1% %line2% %line3%"
echo("%var%"
If you don't know the number of values, use a for /f command to read the lines and concatenate the contents into a variable.
#echo off
setlocal enableextensions enabledelayedexpansion
set "var="
for /f "usebackq delims=" %%a in ("input.txt") do set "var=!var!%%a "
echo("%var%"
But if the data can contain exclamation signs, the delayed expansion state will remove them (and the text surounded by them). To avoid it, this can be used
#echo off
setlocal enableextensions disabledelayedexpansion
set "var="
for /f "usebackq delims=" %%a in ("input.txt") do (
setlocal enabledelayedexpansion
for /f "tokens=* delims=¬" %%b in ("¬!var!") do endlocal & set "var=%%b%%a "
)
echo("%var%"
where the setlocal/endlocal and the inner for are used to avoid problems with ! character
Or you can try something like this
#echo off
setlocal enableextensions disabledelayedexpansion
for /f "delims=" %%a in ('
"<nul cmd /q /c "for /f "usebackq delims=" %%z in ("input.txt"^) do (set /p ".=%%z "^)""
') do set "var=%%a"
echo("%var%"
It runs a cmd instance to output the input lines as only one output line (<nul set /p is used to ouput the data without line feeds, so all data is in the same line). This is wrapped in a for to retrieve the output inside a variable

Would this work for you?
#echo off
SET var=
SETLOCAL EnableDelayedExpansion
FOR /f %%i in (afile.txt) DO (
SET var=!var!%%i
)
echo !var!
ENDLOCAL
Notice there is a space after the SET var=!var!%%i[Space Here] to separate each word in each row
EDIT:
If you want to display the current value in the loop just print %%i with NO concatenation. After the FOR loop finishes it will print the last value assigned to the variable
#echo off
SET var=
SETLOCAL EnableDelayedExpansion
for /f %%i in (input.txt) do (
SET var=%%i
echo !var!
)
echo %var%
Will print:
Bob
Jack
Sam
Sam

Try this: Post Edited.
#Echo off
Set "File=Recent_Log.txt"
Set "Output=My_Log.txt"
(
For /F %%F in (%File%) Do (
Set /p ".=%%~F "
)
) > "%Output%" < Nul
Goto :Eof

Because this is the first link after a Google search, I post my solution(Windows 7/10 .bat):
for %%f in (h:\blaba\*.*) do (type "%%f" & echo.) >> h:\sfsdf\dd.txt
NOTE: When your directory/filename contains spaces use double quotes.

Related

In batch split a string to new lines in file by delimiter

In batch I'm trying to split a string into substrings preferably based on a delimiter.
This example works but is there a better way to do this:
for /f "tokens=1-20 delims=:" %%a in (string.txt) do (
echo %%a& echo.%%b& echo.%%c& echo.%%d& echo.%%e& echo.%%f& echo.%%g& echo.%%h& echo.%%i& echo.%%j
echo.%%k& echo.%%l& echo.%%m& echo.%%n& echo.%%o& echo.%%p& echo.%%q& echo.%%r& echo.%%s& echo.%%t
) >substrings.txt
I have tried this code from Magoo which works for default delimiters but fails using colon:
#echo off
setLocal
for /f "delims=:" %%a in (string.txt) do (
for %%i in (%%a) do echo %%i >>substrings.txt
)
I have also tried this code from Aacini but it seems to fail using special characters.
#echo off
setlocal EnableDelayedExpansion
set i=1
set "x=%string%"
set "x!i!=%x::=" & set /A i+=1 & set "x!i!=%"
set x >substrings.txt
An example %string% var or string.txt is:
Select project:/option:report name="Sustainability":option value="201":Huonville:/option:/report:report name="Energy and Water Management":option value="102":Cygnet:/option:/report:report name="Tree Management":option value="101":Cygnet:/option:/report:option disabled="disabled":/option:/select
I am trying to output %string% var or string.txt to substring.txt as follows:
Select project
/option
report name="Sustainability"
option value="201"
Huonville
/option
/report
report name="Energy and Water Management"
option value="102"
Cygnet
/option
/report
report name="Tree Management"
option value="101"
Cygnet
/option
/report
option disabled="disabled"
/option
/select
Any help would be greatly appreciated. Thanks
When you use for /f, you need to know how many tokens there are (and there is a limit for max tokens).
You need a plain for loop, but you can't choose, which delimiter should be used.
So replace every delimiter with a space. Be sure to have quotes around each "token" to take care of original spaces. To do this, put quotes around the whole string and replace the delimter : with " ":
#echo off
setlocal enabledelayedexpansion
set "string=Select project:/option:report name="Sustainability":option value="201":Huonville:/option:/report:report name="Energy and Water Management":option value="102":Cygnet:/option:/report:report name="Tree Management":option value="101":Cygnet:/option:/report:option disabled="disabled":/option:/select""
set "string=%string: =#%"
set "string="%string::=" "%"
(for %%a in (%string%) do (
set "out=%%~a"
echo !out:#= !
))>out.txt
echo take a look at the modified string:
echo %string%
echo/
type out.txt
Another approach (just for academic reasons):
#echo off
setlocal
set "string=Select project:/option:report name="Sustainability":option value="201":Huonville:/option:/report:report name="Energy and Water Management":option value="102":Cygnet:/option:/report:report name="Tree Management":option value="101":Cygnet:/option:/report:option disabled="disabled":/option:/select"
call :recur %string%
goto :eof
:recur
rem echo loop with %*
for /f "tokens=1,* delims=:" %%a in ("%*") do (
echo %%a
if not "%%~b" == "" call :recur %%b
goto :eof
)
echo.
Note: there is a recursion limit (due to stack-size). It works with the given string, but may fail when the string contains more "tokens".
See #dbenham's AMAZING CERTUTIL string replacement technique. It works for any characters, even exclams!
#echo off
====SETLOCAL EnableDelayedExpansion EnableExtensions
set "B=^!"
set "C=^"
set ^"L=^
%===Line Feed===%
"
for /F "eol=N" %%C in ('wmic os get Name /value') do set "R=%%C" Carriage Return
set ^"E=!R!!L!" CRLF
>nul 2>&1 certutil -f -encodehex String.txt "%temp%\hex.txt" 4
pushd "%temp%"
>expand.txt (FOR /F "delims=" %%A in (hex.txt) do FOR %%B in (%%A) do (
set "char=%%B"
REM ! --> !B! ###
set "char=!char:21=21 42 21!"
REM ^ --> !C! ###
set "char=!char:5e=21 43 21!"
REM <CR> --> !R! ###
set "char=!char:0a=21 4c 21!"
REM <LF> --> !L! ###
set "char=!char:0d=21 52 21!"
REM : --> !R!!L! ###
set "char=!char:3a=21 45 21!"
echo(!char!
))
>nul 2>&1 certutil -f -decodehex expand.txt rawContent.txt
for /f delims^=^ eol^= %%A in (rawContent.txt) do set "modified=%%A"
del hex.txt expand.txt rawContent.txt
popd
>substring.txt (
echo(!modified!
)
This is a summary of what Stephan came up with.
#echo off
setlocal enabledelayedexpansion
set /p string=<"input.txt"
set "string=%string: =#%"
set "string="%string::=" "%"
(for %%a in (%string%) do (
set "output=%%~a"
echo !output:#= !
))>output.txt
Set string or input text file (modify line 3).
set /p string=<"input.txt"
The delimiter in this example is colon [:] which follows after [string:] (modify line 5).
set "string="%string::=" "%"
If string or input.txt contains quotes %string% may need to be double quoted (modify line 3).
for /f "delims=" %%a in (input.txt) do (set string="%%a")
#echo off
setlocal enabledelayedexpansion
for /f "delims=" %%a in (input.txt) do (set string="%%a")
set "string=%string: =#%"
set "string="%string::=" "%"
(for %%a in (%string%) do (
set "output=%%~a"
echo !output:#= !
))>output.txt

windows batch escape whole string

Ok. this is a self updating batch file. I just simplified the problem from a bigger file.
this is a windows batch file(.bat) that upon execution should open itself and update first line
SET variableName=D:\Data
setlocal enableextensions enabledelayedexpansion
set /A i=0
for /f "tokens=*" %%f in ('type "%0"^&cd.^>"%0"') do (
set /A i=!i!+1
if !i! EQU 1 (
echo SET variableName=D:\Data2>>%0
) else (
echo %%f>>%0
)
)
endlocal
so let explain the situation.
i have !i! variable in lines 5 and 6. after executing this file, the variable in each line will replace by line number. it obviously because of echo %%f>>%0 that could not ignore and escape variable.
and my question is how to solve this problem?
another less problem is that the above code ignores spaces at beginning of line (indents) and generates a flat file.
the result of executing this file is:
SET variableName=D:\Data2
setlocal enableextensions enabledelayedexpansion
set /A i=0
for /f "tokens=*" %%f in ('type "%0"^&cd.^>"%0"') do (
set /A i=5+1
if 6 EQU 1 (
echo SET variableName=D:\Data2>>%0
) else (
echo %%f>>%0
)
)
endlocal
Stopping expansion of the variable when executing the file is as simple as turning delayed expansion off prior to the line that updates the file, and pairing it with an endlocal.
Retaining the space / tab formatting is achieved by including delims= in the For loop options.
Set variableName=D:\Data
Setlocal enableextensions enabledelayedexpansion
Set /A i=0
For /f "tokens=* delims=" %%f in ('type "%0"^&cd.^>"%0"') do (
Set /A i+=1
If !i! EQU 1 (
Echo SET variableName=D:\Data2>>%0
) Else (
Setlocal DisableDelayedExpansion
Echo(%%f>>%0
Endlocal
)
)
Endlocal
set "variableName=D:\Data"
setlocal enableextensions enabledelayedexpansion
rem !test! exclaimations, %test% percentages
for /f "skip=1 delims=" %%A in ('
type "%~f0" ^&
^> "%~f0" echo set "variableName=D:\Data2"
') do (
setlocal disabledelayedexpansion
>> "%~f0" echo %%A
endlocal
)
endlocal
You can avoid counting as skip=1 can be used to skip the first line. Use delims= to avoid delimiting the line. tokens=* ignores delimiters at start of the line and get the remainder of the line so that can be omitted for this task.
The new first line is now in the for loop command instead of erasing the file to empty. If you echo more lines, then increase the skip number.
Also may need to use setlocal disabledelayedexpansion so exclamation marks are retained.
Modifying the same file that is being read can a risk, though I assume you understand the risk.

Through a for /f loop added spaces in the saved variable do not show up in the prompt

I have the possibility to Highlight every letter of a Word with the space key.
The delimeter is a for /f Loop Option. The Output of the variablenmae Word, do not show empty spaces. For example the varaiblenames Word, content is THEWORDISPAT is shown with the used code. Until I try to Output A THEWORDISPAT. In such a case the Output is fused ATHEWORDISPAT. I can not Point to search for what I Need. A non english native user.
#echo off
setlocal enabledelayedexpansion
set logic=13
for /l %%a in (1,1,%logic%) do (call :grapefruit %%a)
goto :eof
goto :main
:grapefruit
set count=0
for %%z in (%1) do (
set /a count+=10%3
set var[!count!]=%%z)
:main
set token= THEWORDIZPAT
for /f "tokens=* delims=" %%b in ("%token%") do (set word=%%b)
set alien=!word:~%var[10]%,1!
for %%y in (%alien%) do (echo|set /p =%%y)
pause > nul
endlocal disabledelayedexpasion
Layouts for screen display is seperated in mainly two cases. First case languages and second case to define possible changes.
The solution below is possible but it is not with an upgraded example to the main example.
#echo off
setlocal enabledelayedexpansion
for /f %%A in ('echo prompt $H ^| cmd') do set BS=%%A
set "string=XA THEWORDIZPAT"
for /L %%A in (0,1,14) do (
for /f "tokens=* delims=X" %%b in ("!string:~%%A,1!") do (
set /p=%BS%%%b < nul)
pause > nul
)

MS-DOS batch script: assignment operation

I am referring to below threat Batch files: How to read a file?. For retrieving the line by line from a text file. I am using the below script:
#echo off
SETLOCAL DisableDelayedExpansion
FOR /F "usebackq delims=" %%a in (`"findstr /n ^^ paths.txt"`) do (
set "var=%%a"
SETLOCAL EnableDelayedExpansion
set "var=!var:*:=!"
echo !var!
ENDLOCAL
)
Code is working fine! The values in !var! can not assign to any variable. :( I struct there, Please anyone help to read line by line and I wish to assign to some variable and want to manipulate that variable. Please help to solve this situation.
Update:
#ECHO off
CLS
SET PROJ_DIR=D:\workspace\proj
SET PROMO_DIR=D:\TEST
SET SOURCE_CODE=\Source Code
SETLOCAL DisableDelayedExpansion
for /f %%a in (paths.txt) do (
SET "var=%%a"
SETLOCAL EnableDelayedExpansion
set "var=!var:*:=!"
set FILE_PATH=!var://www.domain.com/path/dir=!
SET FILE_PATH=!FILE_PATH:/=\!
SET PROMO_FILE_PATH=!PROMO_DIR!!SOURCE_CODE!!FILE_PATH!
FOR %%i IN ("!PROMO_FILE_PATH!") DO SET FOLDER_PATH=%%~dpi
FOR %%i IN ("!PROMO_FILE_PATH!") DO SET FILE_NAME=%%~nxi
IF EXIST "!FOLDER_PATH!" GOTO F3
MKDIR "!FOLDER_PATH!"
:F3
IF NOT EXIST "!PROJ_DIR!!FILE_PATH!" GOTO F4
COPY "!PROJ_DIR!!FILE_PATH!" "!FOLDER_PATH!"
:F4
ECHO Cannot find the file under "!PROJ_DIR!!FILE_PATH!"
ENDLOCAL
)
SET CLOSE_CONFIRM=
SET /P CLOSE_CONFIRM=Press any key to close the window...%=%
paths.txt
//www.domain.com/path/dir/dir1/dir2/file1.txt
//www.domain.com/path/dir/dir1/dir2/file2.txt
//www.domain.com/path/dir/dir1/dir2/file3.txt
//www.domain.com/path/dir/dir1/dir2/file4.txt
//www.domain.com/path/dir/dir1/dir3/file1.txt
Command Output
1 file(s) copied.
Cannot find the file under "D:\workspace\proj\dir1\dir2\file1.txt"
1 file(s) copied.
Cannot find the file under "D:\workspace\proj\dir1\dir2\file2.txt"
Press any key to close the window...
thanks..
The key is the delayed expansion, expand your variables inside of parenthesis always with ! not with %.
A sample that changes X with Y
#echo off
SETLOCAL DisableDelayedExpansion
FOR /F "usebackq delims=" %%a in (`"findstr /n ^^ paths.txt"`) do (
set "var=%%a"
SETLOCAL EnableDelayedExpansion
set "var=!var:*:=!"
set "myVar=!var!"
set "myVar=!myVar:X=Y!"
echo X replaced with Y =!myVar!
ENDLOCAL
)
In your updated version the goto :label stops the for-loop immediatly
Better rewrite it to IF-Blocks
IF NOT EXIST "!FOLDER_PATH!" (
MKDIR "!FOLDER_PATH!"
)
IF EXIST "!PROJ_DIR!!FILE_PATH!" (
COPY "!PROJ_DIR!!FILE_PATH!" "!FOLDER_PATH!"
) ELSE
(
ECHO Cannot find the file under "!PROJ_DIR!!FILE_PATH!"
)
The other answers here cover the tricky bits of delayed expansion in this code. I want to add that you can often avoid most delayed expansion problems by rolling the parentheses out into a subroutine.
FOR /F "usebackq delims=" %%a in (`"findstr /n ^^ paths.txt"`) do call :HandlePath %%a
goto :eof
================
:HandlePath
set "var=%*"
set "var=%var:*:=%"
echo %var%
goto :eof
I find this code easier to maintain because each line is parsed an executed exactly when you would expect.
If you want to read each line and manipulate it:
SETLOCAL EnableDelayedExpansion
FOR /F "tokens=*" %%a IN (paths.txt) DO (
set var=%%a
ECHO %var%
PAUSE
)
ENDLOCAL
If you are trying to search a string from a file and manipulate it:
SETLOCAL EnableDelayedExpansion
FOR /F "tokens=* usebackq" %%a IN (`FIND /I 'string to search for' "C:\folder\paths.txt"`) DO (
set var=%%a
ECHO %var%
PAUSE
)
ENDLOCAL
If you are trying to search a string and manipulate each word in the string:
SETLOCAL EnableDelayedExpansion
FOR /F "usebackq tokens=1-999 delims= " %%a IN (`FIND /I 'string to search for' "C:\folder\paths.txt"`) DO (
REM %%a = first word %%b = second word etc. through the alphabet
set var1=%%a%%b%%c
set var2=%%d
ser var3=%%e
ECHO %var1% %var2% %var3%
PAUSE
)
ENDLOCAL
This works for me:
#echo off
SETLOCAL EnableDelayedExpansion
FOR /F "usebackq delims=" %%a in (`"findstr /n ^^ paths.txt"`) do (
set var=%%a
set var=!var:*:=!
echo !var!
)
ENDLOCAL

Assign output of a program to a variable using a MS batch file

I need to assign the output of a program to a variable using a MS batch file.
So in GNU Bash shell I would use VAR=$(application arg0 arg1). I need a similar behavior in Windows using a batch file.
Something like set VAR=application arg0 arg1.
Similar Questions
How to set commands output as a variable in a batch file
How do I get the result of a command in a variable in windows?
Set the value of a variable with the result of a command in a Windows batch file
Set output of a command as a variable (with pipes)
Assign command output to variable in batch file
One way is:
application arg0 arg1 > temp.txt
set /p VAR=<temp.txt
Another is:
for /f %%i in ('application arg0 arg1') do set VAR=%%i
Note that the first % in %%i is used to escape the % after it and is needed when using the above code in a batch file rather than on the command line. Imagine, your test.bat has something like:
for /f %%i in ('c:\cygwin64\bin\date.exe +"%%Y%%m%%d%%H%%M%%S"') do set datetime=%%i
echo %datetime%
As an addition to this previous answer, pipes can be used inside a for statement, escaped by a caret symbol:
for /f "tokens=*" %%i in ('tasklist ^| grep "explorer"') do set VAR=%%i
When executing the following in the command line:
for /f %%i in ('application arg0 arg1') do set VAR=%%i
I was getting the error:
%%i was unexpected at this time.
To fix, I changed to use a single % sign like this:
for /f %i in ('application arg0 arg1') do set VAR=%i
Summary:
Use %% when in a batch file
Use % when outside a batch file (on a command line)
#OP, you can use for loops to capture the return status of your program, if it outputs something other than numbers
You could use a batch macro for simple capturing of command outputs, a bit like the behavior of the bash shell.
The usage of the macro is simple and looks like:
%$set% VAR=application arg1 arg2
it also works even with pipes:
%$set% allDrives="wmic logicaldisk get name /value | findstr "Name""
The macro uses the variable like an array and stores each line in a separate index.
In the sample of %$set% allDrives="wmic logicaldisk" there will the following variables created:
allDrives.Len=5
allDrives.Max=4
allDrives[0]=Name=C:
allDrives[1]=Name=D:
allDrives[2]=Name=F:
allDrives[3]=Name=G:
allDrives[4]=Name=Z:
allDrives=<contains the complete text with line feeds>
To use it, it's not important to understand how the macro itself works.
The full example:
#echo off
setlocal
call :initMacro
%$set% ipOutput="ipconfig"
call :ShowVariable ipOutput
echo First line is %ipOutput[0]%
echo(
%$set% driveNames="wmic logicaldisk get name /value | findstr "Name""
call :ShowVariable driveNames
exit /b
:ShowVariable
setlocal EnableDelayedExpansion
for /L %%n in (0 1 !%~1.max!) do (
echo %%n: !%~1[%%n]!
)
echo(
exit /b
:initMacro
if "!!"=="" (
echo ERROR: Delayed Expansion must be disabled while defining macros
(goto) 2>nul
(goto) 2>nul
)
(set LF=^
%=empty=%
)
(set \n=^^^
%=empty=%
)
set $set=FOR /L %%N in (1 1 2) dO IF %%N==2 ( %\n%
setlocal EnableDelayedExpansion %\n%
for /f "tokens=1,* delims== " %%1 in ("!argv!") do ( %\n%
endlocal %\n%
endlocal %\n%
set "%%~1.Len=0" %\n%
set "%%~1=" %\n%
if "!!"=="" ( %\n%
%= Used if delayed expansion is enabled =% %\n%
setlocal DisableDelayedExpansion %\n%
for /F "delims=" %%O in ('"%%~2 | findstr /N ^^"') do ( %\n%
if "!!" NEQ "" ( %\n%
endlocal %\n%
) %\n%
setlocal DisableDelayedExpansion %\n%
set "line=%%O" %\n%
setlocal EnableDelayedExpansion %\n%
set pathExt=: %\n%
set path=; %\n%
set "line=!line:^=^^!" %\n%
set "line=!line:"=q"^""!" %\n%
call set "line=%%line:^!=q""^!%%" %\n%
set "line=!line:q""=^!" %\n%
set "line="!line:*:=!"" %\n%
for /F %%C in ("!%%~1.Len!") do ( %\n%
FOR /F "delims=" %%L in ("!line!") Do ( %\n%
endlocal %\n%
endlocal %\n%
set "%%~1[%%C]=%%~L" ! %\n%
if %%C == 0 ( %\n%
set "%%~1=%%~L" ! %\n%
) ELSE ( %\n%
set "%%~1=!%%~1!!LF!%%~L" ! %\n%
) %\n%
) %\n%
set /a %%~1.Len+=1 %\n%
) %\n%
) %\n%
) ELSE ( %\n%
%= Used if delayed expansion is disabled =% %\n%
for /F "delims=" %%O in ('"%%~2 | findstr /N ^^"') do ( %\n%
setlocal DisableDelayedExpansion %\n%
set "line=%%O" %\n%
setlocal EnableDelayedExpansion %\n%
set "line="!line:*:=!"" %\n%
for /F %%C in ("!%%~1.Len!") DO ( %\n%
FOR /F "delims=" %%L in ("!line!") DO ( %\n%
endlocal %\n%
endlocal %\n%
set "%%~1[%%C]=%%~L" %\n%
) %\n%
set /a %%~1.Len+=1 %\n%
) %\n%
) %\n%
) %\n%
set /a %%~1.Max=%%~1.Len-1 %\n%
) %\n%
) else setlocal DisableDelayedExpansion^&set argv=
goto :eof
assuming that your application's output is a numeric return code, you can do the following
application arg0 arg1
set VAR=%errorlevel%
In addition to the answer, you can't directly use output redirection operators in the set part of for loop (e.g. if you wanna hide stderror output from a user and provide a nicer error message). Instead, you have to escape them with a caret character (^):
for /f %%O in ('some-erroring-command 2^> nul') do (echo %%O)
Reference: Redirect output of command in for loop of batch script
#echo off
SETLOCAL ENABLEDELAYEDEXPANSION
REM Prefer backtick usage for command output reading:
REM ENABLEDELAYEDEXPANSION is required for actualized
REM outer variables within for's scope;
REM within for's scope, access to modified
REM outer variable is done via !...! syntax.
SET CHP=C:\Windows\System32\chcp.com
FOR /F "usebackq tokens=1,2,3" %%i IN (`%CHP%`) DO (
IF "%%i" == "Aktive" IF "%%j" == "Codepage:" (
SET SELCP=%%k
SET SELCP=!SELCP:~0,-1!
)
)
echo actual codepage [%SELCP%]
ENDLOCAL
I wrote the script that pings google.com every 5 seconds and logging results with current time. Here you can find output to variables "commandLineStr" (with indices)
#echo off
:LOOPSTART
echo %DATE:~0% %TIME:~0,8% >> Pingtest.log
SETLOCAL ENABLEDELAYEDEXPANSION
SET scriptCount=1
FOR /F "tokens=* USEBACKQ" %%F IN (`ping google.com -n 1`) DO (
SET commandLineStr!scriptCount!=%%F
SET /a scriptCount=!scriptCount!+1
)
#ECHO %commandLineStr1% >> PingTest.log
#ECHO %commandLineStr2% >> PingTest.log
ENDLOCAL
timeout 5 > nul
GOTO LOOPSTART
Some macros to set the output of a command to a variable/
For directly in the command prompt
c:\>doskey assign=for /f "tokens=1,2 delims=," %a in ("$*") do #for /f "tokens=* delims=" %# in ('"%a"') do #set "%b=%#"
c:\>assign WHOAMI /LOGONID,my-id
c:\>echo %my-id%
Macro with arguments
As this macro accepts arguments as a function i think it is the neatest macro to be used in a batch file:
#echo off
::::: ---- defining the assign macro ---- ::::::::
setlocal DisableDelayedExpansion
(set LF=^
%=EMPTY=%
)
set ^"\n=^^^%LF%%LF%^%LF%%LF%^^"
::set argv=Empty
set assign=for /L %%n in (1 1 2) do ( %\n%
if %%n==2 (%\n%
setlocal enableDelayedExpansion%\n%
for /F "tokens=1,2 delims=," %%A in ("!argv!") do (%\n%
for /f "tokens=* delims=" %%# in ('%%~A') do endlocal^&set "%%~B=%%#" %\n%
) %\n%
) %\n%
) ^& set argv=,
::::: -------- ::::::::
:::EXAMPLE
%assign% "WHOAMI /LOGONID",result
echo %result%
FOR /F macro
not so easy to read as the previous macro.
::::::::::::::::::::::::::::::::::::::::::::::::::
;;set "{{=for /f "tokens=* delims=" %%# in ('" &::
;;set "--=') do #set "" &::
;;set "}}==%%#"" &::
::::::::::::::::::::::::::::::::::::::::::::::::::
:: --examples
::assigning ver output to %win-ver% variable
%{{% ver %--%win-ver%}}%
echo 3: %win-ver%
::assigning hostname output to %my-host% variable
%{{% hostname %--%my-host%}}%
echo 4: %my-host%
Macro using a temp file
Easier to read , it is not so slow if you have a SSD drive but still it creates a temp file.
#echo off
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
;;set "[[=>"#" 2>&1&set/p "&set "]]==<# & del /q # >nul 2>&1" &::
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
chcp %[[%code-page%]]%
echo ~~%code-page%~~
whoami %[[%its-me%]]%
echo ##%its-me%##
This answer may help as well : https://stackoverflow.com/a/61666083/2444948
But it is actually writing a file to read it ...
The code is not from me:
(cmd & echo.) >2 & (set /p =)<2
REM Example :
(echo foo & echo.) >2 & (set /p bar=)<2
//set str=%myVar:*:=%// this replace all before ":" to " "                                                        
//findstr "Subnet Mask" my_log.txt > my_find.txt// search "string" in file and save in new file
//">" remake file, if use ">>" add in old file// im recommend use ">"
#echo off
ipconfig > my_log.txt
findstr "Subnet Mask" my_log.txt > my_find.txt
set /p myVar= < my_find.txt
echo %myVar%
set str=%myVar:*:=%
set str=%str:.= im_dot %
echo %str%
pause

Resources