batch file, creating numbering list - batch-file

I have created a batch file that stores log info, so let say you enter username and pass, it is encrypted and stored on a text file, that works great, the text is stored in this format:
xewiofjeoijfe
casowc43pcj89
And so on, i just used random text by the way on the above lines to use as example, so every new line of text is added to the bottom of the text file, what I'd like to do is that every time a new line is added, is added with a number or name and number, like so:
username1 fewfuhvruivhriuvew
username2 erwve9p8rvejp9
username3 vj39gew4tg000904t3[0g9i40
How can i accomplish this?

If I understand what it is you want to do this should be close:
#echo off
set "LogFile=Test.txt"
if not exist "%LogFile%" type nul>"%LogFile%" & rem this line needed to create empty file if file does not exist
set "YourLoggedInfo=SomeInfoYouLogged" & rem this line will be replaced by what you are currently logging
rem below we will get number of existing lines and add 1
set /a LastLine=0
for /f "usebackq tokens=1 delims=:" %%a in (`findstr /n . "%LogFile%"`) do set /a LastLineNum=%%a
set /a LastLineNum+=1
rem replace %YourLoggedInfo% in the line below with what you are currently logging
echo(Username%LastLineNum% %YourLoggedInfo% >>"%LogFile%"

Related

Batch Scripting Properties file

this has to be done in batch.
I need to be able to read an input file, and parse out certain sections only of lines that contain a specific string, then write that to an output file. For example:
input =test.properties file
SQL
Datamodel
sale_detail.sql
bpid_exclusion.sql
expected output =
SQL
Datamodel
sale_detail.sql
bpid_exclusion.sql
This is what I have so far:
#setlocal enableextensions enabledelayedexpansion
set
log_filepath=PATH/config.sql
FOR /F "usebackq tokens=* delims=" %%A IN (test.properties) DO (
set temp=%%A
ECHO %%A >> %log_filepath%
The problem I have right now is that when I run this script, it's printing the complete properties file, but what i want is after reading the file it should check if the word SQL exists in the file or not if yes it should check for the next word datamodel if data model exists it should print the next two lines which is sale_Detail.sql and bpid_exclusion.sql in the log_filepath
Your question is unclear, but I am guessing you have a file with filenames. If the filename in the file exists in a directory echo the content. If that is the case, try this.
#echo off
Set "infile=%~dp0test1.properties"
set "log_filepath=d:\somedir\logfile.log"
for /f "delims=" %%a in (%infile%) do If exist "%%a" type "%%a" >> %log_filepath%

Batch file redirection to text file not working inside for loop

REM timestamped name of file
set PREFIX=LINE_
set SAVESTAMP=%PREFIX%%DATE:/=-%_%TIME::=-%
set SAVESTAMP=%SAVESTAMP: =%
set SAVESTAMP=%SAVESTAMP:,=.%.txt
echo %SAVESTAMP%
REM In H.txt, for each line grab the text after delimiter ':' and send it to file
for /f "tokens=2 delims=:" %%a in ('type D.txt^|find ":"') do (
set line=%%a
REM#1
echo %line% >> %SAVESTAMP%
)
REM#2
REM echo %line% >> %SAVESTAMP% ---This output one line
When I use REM#1 and comment the second echo outside the for loop, there is not file created.
But when I use REM#2 and don't use REM#1 echo a file with one line is created.
Most times the file will have multiples lines written to it.
So I want this working inside the for loop.
D.txt
line1:sample1
line2:sample2
line3:sample3
line4:sample4
Output should be :
Line_Date_TimeStamp.txt
sample1
sample2
sample3
sample4
Two problems:
First, there must be a separator (like a space) between rem and the text, otherwise an attempt to find and execute an executable named rem#1.(bat,exe etc.) is made.
Second, you need to search SO for delayed expansion as you are attempting to show the value of a variable (line) that is being modified within the for block.

How to populate undetermined number of variables from text file?

So I know how to save strings to a text file as a list from batch by using
set /p Myvar1="Enter your variable name/value: "
set /p Myvar2="Enter your variable name/value: "
set /p Myvar3="Enter your variable name/value: "
And then append to a text file
echo %Myvar1% %Myvar2% %Myvar3% >> Mylist.txt
So when I open the text file through the batch file, it can be displayed
as a list:
SET "variables="
ECHO =================================================
ECHO My list of stuff
ECHO =================================================
< Mylist.txt (
set /p MyVar1=
set /p MyVar2=
set /p MyVar3=
)
::set line
ECHO - [0] - %Myvar1%
ECHO - [1] - %Myvar1%
ECHO - [2] - %Myvar1%
Now the problem is that:
For each new line on the Mylist.txt text file I have to manually add lines on the batch file. On the provided example the batch is setup so it displays 3 lines of text from the text file. If the text file has 10 lines, it will only show the first 3 lines because that is what is specified. So I would like to accomplish the opposite of this script.
The batch file should be able to:
Batch file reads Mylist.txt.
For each line in Mylist.txt file the batch file creates a "numerated variable".
Each "numerated variable" can be addressable so the user can be prompted to select one of the options on the list 1, 2, 3, 4, etc.
The easiest method to save variable names and their values to a file is redirecting the output of command SET to a file.
set My >"%APPDATA%\MyVariables.txt"
This simple line saves all environment variables starting with My in name with name and value into file MyVariables.txt in application data directory of current user.
And following command line can be used in a batch file to reload those environment variables from file:
for /F "usebackq delims=" %%I in ("%APPDATA%\MyVariables.txt") do set "%%I"
Same command line for usage directly in a command prompt window:
for /F "usebackq delims=" %I in ("%APPDATA%\MyVariables.txt") do set "%I"
A little bit more secure would be checking if each line in the file MyVariables.txt really starts with My as expected and so was not manipulated by someone who wants to override for example PATH by adding manually to file MyVariables.txt a line starting with PATH=.
It might be useful to know how many variables were loaded from file. This can be achieved with a simple extension:
set "VariablesCount=0"
for /F "usebackq delims=" %%I in ("%APPDATA%\MyVariables.txt") do set "%%I" & set /A VariablesCount+=1
Of course if there is an environment variable MyVariablesCount starting with My then this variable with its value would be also saved into the file and reloaded from file which would make it unnecessary to count the number of variables set from file.
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.
for /?
set /?
Read also the Microsoft article about Using Command Redirection Operators.
simple thing with a for loop plus a counter:
setlocal enabledelayedexpansion
set i=0
for /f "delims=" %%a in (mylist.txt) do (
set /a i+=1
set var[!i!]=%%a
)
echo number of variables: %i%:
set var[
echo ---------
for /l %%a in (1,1,%i%) do echo variable %%a = %var[%%a]%

Batch file commands - Findstr, splitting and file name variables

I'm kind of new to batch commands and have been trying to automate something we do manually. I have a log file that is downloaded every day, then I search for certain items in it using Findstr (output to another file) and then split what was found into smaller files.
I'm having trouble with making file names and file name variables and using it throughout my code. The splitter code was given to me, so I'm just trying to incorporate Findstr into it. Any tips or see what I'm doing wrong?
Example:
Campaign ID: 1234
Campaign Name: Pepsi
Impression Filename: 10-06-16_file.log
Day of week: 2
It will look through 10-06-16_file.log for any rows with Campaign ID 1234 and output them to fnd_10-06-16_file.log.
If fnd_10-06-16_file.log filesize is greater than 177000kb then split the file into smaller files with name 2SplitFile1_Pepsi.log, 2SplitFile2_Pepsi.log, 2SplitFile3_Pepsi.log, etc.
setlocal ENABLEDELAYEDEXPANSION
#echo off
REM Ask for Campaign information to find
SET /P campaignid="Campaign ID(s): "
SET /P campaignname="Campaign Name: "
SET /P impressionfile="Impression Filename: "
SET /P dayofweek="Day of week: "
SET fnd_impressionfile=%campaignname%_%impressionfile%
SET maxbytesize=177000
SET fnd_impressionfile_sz=%%~zfnd_impressionfile
REM Find campaigns inside log file
findstr "%campaignname%" %impressionfile% > %fnd_impressionfile%
REM Split log file if greater than 177000 kb
if fnd_impressionfile_sz > maxbytesize (
REM Edit this value to change the name of the file that needs splitting. Include the extension.
SET BFN=%fnd_impressionfile%
REM Edit this value to change the number of lines per file.
SET LPF=1000000
REM Edit this value to change the name of each short file. It will be followed by a number indicating where it is in the list.
SET SFN=SplitFile
REM Do not change beyond this line.
SET SFX=%BFN:~-3%
SET /A LineNum=0
SET /A FileNum=1
For /F "delims=" %%l in (%BFN%) Do (
SET /A LineNum+=1
echo %%l >> %dayofweek%%SFN%!FileNum!_%campaignname%.%SFX%
if !LineNum! EQU !LPF! (
SET /A LineNum=0
SET /A FileNum+=1
)
)
)
endlocal
pause
First, change SET fnd_impressionfile_sz=%%~zfnd_impressionfile to FOR %%a in (%fnd_impressionfile%) DO SET fnd_impressionfile_sz=%%~za
Then, double check you maxbytesize. Your description says kb, but the batch implies byte. fnd_impressionfile_sz contains the byte value.
The other thing I see is there you're using the redirection operator > in if fnd_impressionfile_sz > maxbytesize. You should change it to GTR or GEQ. See HELP IF.

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.

Resources