Add all contents of a file in a single variable in Batch - batch-file

Suppose I have a text file with following contents:
Hello
World
Abc
Now I want to read this in batch and copy them into a single variable. So my variable should contain:
var=Hello World Abc
What is possible work around for this?
If I am trying I am either getting the first word or the last line word.
Thanks

This seems to work. I have appended \n to each line in the read file. I'm not sure how you expect that behavior to actually work:
#echo off
SETLOCAL EnableDelayedExpansion
set "filecontents="
for /f "delims=" %%x in (input.txt) do (
set filecontents=!filecontents!%%x\n
)
echo %filecontents%

To read the contents of a file in a batch file you can use a FOR /F command. You then use the SET command to assign a value to a variable. Also, you will need to utilized delayed expansion to reassign the existing variable to the original variable. A leading space will get assigned so the echo command is using a substring to remove it.
#echo off
setlocal EnableDelayedExpansion
for /f "delims=" %%G IN (file.txt) do set "var=!var! %%G"
echo %var:~1%

Related

How to delete all words after a specific word in batch file

I have a text file named myfile.txt and it has the following text-
Hi my cry die fly
I want to delete all the words after cry.
Please help
Something like this do:
#echo off
setlocal enabledelayedexpansion
for /f "usebackq delims=" %%i in ("myfile.txt") do (
set "line=%%i"
set "line_excl=!line:*cry=!"
call echo %%line:!line_excl!=%%
)
It sets each line in the file as a value to the a variable called %line%, delayedexpansion is needed however, so we enable it and then use the variable as !line!.
We set a search replace variable to be everything up to cry and then simply set echo the !line! by excluding the remaining part, which is everything after cry.

Combine lines in text file using batch

I want to make a program that takes the content of the second line of a text file and puts it on the first. (It doesn't matter if the second doesn't get edited)
for /f "tokens=1" %%t in (file.txt) do set string1=%%t
for /f "tokens=2" %%t in (file.txt) do set string2=%%t
echo %string1%%string2%>file.txt
I have two issues hat I can't seem to be able to fix.
One: the loops only include the first word of each line in the variables.
Two: Echo doesn't replace the first line of the file with the variables given and instead writes ECHO command deactivated (I have the French version of Windows 10 and simply translated what got written in the file, the text in English Windows version might be slightly different, but you get the idea)
If you have any suggestions, I would appreciate if you explain what the code you provide does (I always like to learn)
Your question is not clear and can be understood in several different ways. Anyway, this management is simpler with no for command:
#echo off
setlocal EnableDelayedExpansion
< file.txt (
rem Takes the content of the first line
set /P "line1="
rem Takes the content of the second line and puts it on the first
set /P "line2="
echo !line1!!line2!
rem It doesn't matter if the second line doesn't get edited
echo !line2!
rem Copy the rest of lines
findstr "^"
) > output.txt
move /Y output.txt file.txt
The FOR command uses a space as a delimiter by default. So you have to tell it to not use any delimiters with the DELIMS option. Also, you should be able to do this with a single FOR /F command. Just hold the previous line in a variable.
#ECHO OFF
setlocal enabledelayedexpansion
set "line1="
(for /f "delims=" %%G in (file.txt) do (
IF NOT DEFINED line1 (
set "line1=%%G"
) else (
echo !line1!%%G
set "line1="
)
)
REM If there are an odd amount of lines, line1 will still be defined.
IF DEFINED line1 echo !line1!
)>File2.txt
EDIT: I think I completely misunderstood your question. Once you clarify your question I will repost a code solution if needed.
Use skip to omit the first line and write the 2nd line twice. In general an edit of a file implies a rewrite to a new file and possibly a rename to retain the old file name.
:: Q:\Test\2018\07\25\SO_51508268.cmd
#Echo off
Set "flag="
( for /f "usebackq skip=1 delims=" %%A in ("file1.txt") Do (
If not defined flag (
Echo=%%A
Set flag=true
)
Echo=%%A
)
) >file2.txt
Del file1.txt
Ren file2.txt file1.txt
After running the batch a file1.txt with initially numbered lines 1..5 looks like this:
> type file1.txt
2
2
3
4
5

Batch script Read multi line Argument in Variable

I wanted to take list of files to delete from user as a argument. One line per argument.
How can store the list of files separated by new line in a variable.
I am using below command.
Set DeletionFiles=${p:DeleteFiles}"
for %%i in (%DeletionFiles%) do (
echo %%i
)
Then i wanted to iterated them on a loop.
${p:DeleteFiles} will get replaced by it's value from external app, which will contain list of files separated by new line.I can not change it.
#ECHO OFF
SETLOCAL
SET "deletionfiles="
:dloop
SET "deleteme="
SET /p "deleteme=Which file to delete ? "
IF DEFINED deleteme SET "deleteme=%deleteme:"=%"
IF DEFINED deleteme SET "deletionfiles=%deletionfiles%,"%deleteme%""&goto dloop
ECHO delete %deletionfiles:~1%
GOTO :EOF
There is no need to use a newline. Your for command (or a del command) will operate perfectly happily on a comma-(or space-)separated list.
Note that there are certain characters that batch uses for special purposes and batch string-processing may not process them in the expected manner. These characters include % ^ and &.
${p:DeleteFiles} will get replaced by it's value from external app,
which will contain list of files separated by new line.I can not
change it.
After the replacement the batch file looks like:
Set DeletionFiles=file1.jpg
file2.jpg
file3.jpg
"
This isn't a valid batch file anymore.
Furthermore it's a bad idea to modify the batch file itself, as this works only once.
You could place the ${p:DeleteFiles} into another file, like input.txt.
Your batch would look like
echo ${p:DeleteFiles} > input.txt
<external program for replacing the DeleteFiles> input.txt
for /F "tokens=*" %%A in (input.txt) do (
echo File: %%A
)
If I understand you correctly, your external program will generate a list of files. You then want to store this multi-line list to a variable. What do you want to do with the variable once you have it? I assume you want to delete the files, but your question isn't clear on that point, so I'll try to over-answer to cover it.
for /f "delims=" %%a in ('{command that generates your list}') do (
echo Doing stuff to %%a...
echo %%a>>listOfFilesToDelete.txt
set var=%%a
if "%var:~0,7%"="DoNotDelete" copy "%%a" \someArchiveFolder\
del "%%a"
)
This will read each line in your generated list as variable %%a. It will then do whatever command(s) you specify. This way, you can run a command on each of the files in the list. In the above code it's
Printing each line to the console embedded in some text
Outputting it to a file
Checking the first 7 characters of the line against a specified string and then copying it to a folder if it matches
And then deleting it
If you still need to reference each line from your generated list, you can even setup an array-like structure. (See Create list or arrays in Windows Batch)
setlocal EnableDelayedExpansion
:: Capture lines in an 'array'
set /a i=0
for /f "delims=" %%a in ('dir /b') do (
set /a i+=1
set var!i!=%%a
)
:: Loop through the 'array'
for /L %%a in (1,1,%i%) do (
echo Do more stuff with !var%%a!
)
Just like above, this will read each line in your generated list as variable %%a. It will then set a variable var!i! equal to the value of the current line. You can then reference each line as var1, var2, and so on, or, as the second section shows, you can loop through them all using for /L. You'll need to get a grasp on working with delayed expansion variables, though.

How to concatenate multiple lines of log file into single variable in batch file?

I have a log file containing a stack trace split over a number of lines. I need to read this file into a batch file and remove all of the lines breaks.
As a first step, I tried this:
if exist "%log_dir%\Log.log" (
for /F "tokens=*" %%a in ("%log_dir%\Log.log") do #echo %%a
)
My expectation was that this would echo out each line of the log file. I was then planning to concatenate these lines together and set that value in a variable.
However, this code doesn't do what I would expect. I have tried changing the value of the options for delims and tokens, but the only output I can get is the absolute path to the log file and nothing from the contents of this file.
How can I set a variable to be equal to the lines of text in a file with the line breaks removed?
If you want to use quotes for your filename in the FOR/F loop you need to add the usebackq option too, else you get a string not the content of your file.
for /F "usebackq delims=" %%a in ("%log_dir%\Log.log") do #echo %%a
Or remove the quotes
if exist "%log_dir%\Log.log" (
for /F "tokens=*" %%a in (%log_dir%\Log.log) do #echo %%a
)

How to get output of a FOR loop into a variable in a batch file

I have a file like this, that needs to be parsed and needs to extract a version number.
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
[assembly: AssemblyFileVersion("0.4.2")]
...
...
I need to parse it and extract the 0.4.2 from it.
I have to do this in windows batch file only. I did this the following way, but I know this is NOT the best way.
setlocal enabledelayedexpansion
SET VERSIONSTR=
REM This is an ugly way to do this, because due to some reason I cant save output of for loop to a variable
REM I would like this in a variable instead of a temp file.
FOR /f "tokens=2*" %%j in (AssemblyInfo.cs) do #echo %%j >> tempfile.txt
REM The "AssemblyFileVersion" line has the version number.
REM I would like this in a variable instead of a temp file.
FOR /f %%i in (tempfile.txt) do #echo %%i | find "AssemblyFileVersion" >> anothertempfile.txt
REM Now this for loop will set a variable.
FOR /f %%k in (anothertempfile.txt) do set VERSIONSTR=%%k
REM Now the line is `AssemblyFileVersion("0.4.2")]` so, I am getting the substring from 21st character
REM till the end and then removing last 3 characters, getting us the string 0.4.2
SET VERSIONSTR=!VERSIONSTR:~21,-3!
I hate having this ugliness in my code, any ideas on how I can modify this? At the very least I would like to know a way for me to get the output of a for loop in a variable in windows batch file.
for /f "tokens=2 delims=()" %%a in ('findstr AssemblyFileVersion AssemblyInfo.cs') do set Version=%%~a
echo %Version%
It got a little ugly because I cannot (apparently) use quotation marks as delimiters, so I chose the parentheses and removed the quotes with %%~x. You can avoid all temporary files here, by the way.
The code above just directly grabs the appropriate line (with findstr) and tokenizes it with for /f.

Resources