Batch to Print specific lines of text to a file - windows

Let me start off by saying I am very new to this, and what little code I have cobbled together I found on this site.
In the end I need a batch that when ran will grab each folder name in a parent dir. and copy it to a text file named label1, label2, ect.
I started with pulling the lines from a directory list in a text file. I can get it to echo the last line to a file using Seth's code from this post
Windows Batch file to echo a specific line number
I made some modifications to try to put it in a loop and now I get nothing out.
If anyone can help me it would be much appreciated. Here is my code so far.
set /a "x=1"
set /a "lines=91"
:while1
if %x% leq %lines% (
for /f "tokens=*" %%a in ('findstr /n .* "Y:\Test\foldernametest.txt"') do (
set "FullLine=%%a"
for /f "tokens=1* delims=:" %%b in ("%%a") do (
setlocal enabledelayedexpansion
set "LineData=!FullLine:*:=!"
if "%%b" equ "%1" echo(!LineData!
echo title=!linedata! > Lable%x%.dat
set /a "x= x+1"
endlocal
goto :while1
)
)

setlocal enabledelayedexpansion
set /a x=1
set /a lines=91
:while1
if %x% leq %lines% (
for /f "tokens=*" %%a in ('findstr /n .* "Y:\Test\foldernametest.txt"') do (
for /f "tokens=1* delims=:" %%b in ("%%a") do (
if "%%b" equ "%x%" (
echo(%%c
echo title=%%c > Lable%x%.dat
set /a x= x+1
goto while1
)
)
)
endlocal
I'm reasonably sure this will work, as would
setlocal enabledelayedexpansion
set /a x=1
set /a lines=91
:while1
if %x% leq %lines% (
for /f "tokens=1* delims=:" %%a in ('findstr /n .* "Y:\Test\foldernametest.txt"') do if %%a==%x% (
echo(%%b
echo title=%%b > Lable%x%.dat
set /a x= x+1
goto while1
)
)
endlocal
The issue with your code is that endlocal terminates a setlocal and all of the environment changes that have taken place since the setlocal are backed out - the environment is restored to what it was when the setlocal was executed.
The consequence is that with your code, you are incrementing x (a grand name for a variable) and then the increment is backed out when the endlocal is executed.
So - put the entire routine in a setlocal/endlocal bracket. This has other advanteages - like if you execute a setlocal immediately after #echo off, then when the routine terminates, the environment is returned to its original state - it does not accumulate changes (normally additions of variables) as more and more batches are run.
Some of the other changes I've made are cosmetic. the quotes in a set /a are superfluous and so is the colon in a goto (with the sole exception of goto :eof)
Another problem you have was %1 (meaning "the first parameter to the routine") where you probably meant "%x%".
In the first code fragment, the output of the findstr is assigned to %%a and the inner for assigns that part of the findstr before the delimiter to %%b and that after to %%c. You evidently want to pick the line %%b equal to %x% so the code makes the comparison and if equal, outputs %%c (rest of line) and title=%%c to the file made from Lable and the line number. (You've spelled label incorrectly); then increments x and tries again.
The second piece of code is a simplification of the first. The line is read from the file and numbered, then split directly on the colon; %%a gets the number, %%b the rest of the line, so if %%a is the same as the number %x% then we want to do something (no quotes required, since %%a is a simple numeric string and x will also be numeric because it's never assigned to a string containing separators or empty).
The thing-to-be-done is to echo the line from the file (in %%b, bump the line number and start again...

Related

Bat file that copy text.files after applying 2 filters

I'm a biologist, with no coding knowledge, trying to create a script that reads every *rprt.txt file in a folder.
In line 11 of each file, the fifth word is a number, If that number is 6000<number<14000 then I want to read the fifth word in line 13 and if that number is greater than 600. Copy the file into another folder in that directory.
At this point I've tried a lot of things. I know the next code is exiting the loop but is the best I got.
#echo off
for %%f in (*rprt.txt) do set "name=%%f" &goto first
:first
for /F "skip=10 tokens=5" %%i in (%name%) do set "var1=%%i" &goto nextline
:nextline
for /F "skip=12 tokens=5" %%i in (%name%) do set "var2=%%i" &goto nextline2
:nextline2
if %var1% geq 6000 (if %var2% geq 600 echo.%name% >> valid.txt)
I've also tried this to test the for loop but I don't understand what's wrong. This prints "echo is off" 3 times
#echo off
for %%f in (*rprt.txt) do (set "name=%%f" & echo %name% >> valid.txt)
#ECHO OFF
SETLOCAL
rem The following settings for the directories and filenames are names
rem that I use for testing and deliberately includes spaces to make sure
rem that the process works using such names. These will need to be changed to suit your situation.
SET "sourcedir=u:\your files"
SET "destdir=u:\your results"
FOR %%e IN ("%sourcedir%\*rprt.txt") DO (
rem %%e has filename
SET "line11="
FOR /f "usebackqskip=10tokens=5" %%y IN ("%%e") DO IF NOT DEFINED line11 (
SET "line11=y"
SET "line13="
FOR /f "usebackqskip=12tokens=5" %%o IN ("%%e") DO IF NOT DEFINED line13 (
SET "line13=y"
IF %%y gtr 6000 IF %%y lss 14000 IF %%o gtr 600 ECHO COPY "%%e" "%destdir%"
)
)
)
GOTO :EOF
Always verify against a test directory before applying to real data.
Note that if the filename does not contain separators like spaces, then both usebackq and the quotes around "%%e" can be omitted.
I'm assuming that the values in token 5 of the two lines are guaranteed numeric.
You were definitely on the right track, but the code for validating that something is a number can get kinda weird if you're not used to seeing it (in this case, I remove everything that isn't a digit and then return 1 if there's anything remaining) and the way that GTR and LSS work can also be confusing since it's based on ASCII values so words report as greater than numbers.
The script expects the reports to be in their own folder and the output folder to be in its own folder, and both of these folders should be in the same folder as the script, as opposed to the script being in the same folder as the input files.
#echo off
setlocal enabledelayedexpansion
set "input_directory=%~dp0\input"
set "output_directory=%~dp0\output"
pushd "%input_directory%"
for %%A in (*_rprt.txt) do (
for /f "tokens=5" %%B in ('findstr /n /r "^" "%%~A" ^| findstr "11:"') do set "line_11_num=%%B"
for /f "tokens=5" %%B in ('findstr /n /r "^" "%%~A" ^| findstr "13:"') do set "line_13_num=%%B"
call :isNumber !line_11_num! n[11]
call :isNumber !line_13_num! n[13]
set /a "valid_report=!n[11]!+!n[13]!"
if "!valid_report!"=="0" (
if !line_11_num! GTR 6000 if !line_11_num! LSS 14000 (
if !line_13_num! GTR 600 (
copy "%%~A" "%output_directory%"
)
)
)
)
exit /b
::------------------------------------------------------------------------------
:: Determines if a given string is a positive integer
::
:: Arguments: %1 - The value to check
:: %2 - The variable to store the result in
:: Returns: 0 if the number is a positive integer, 1 otherwise
::------------------------------------------------------------------------------
:isNumber
set "is_number=0"
for /f "delims=0123456789" %%A in ("%~1") do set "is_number=1"
set "%~2=%is_number%"
exit /b
The files and lines processed by for /F command must be processed completelly until the file ends; you can not "cut" the process at the middle with a goto command because the whole process is cancelled.
This means that all lines of all files must be processed with nested for /F commands and you must insert some type of control in order to "omit" the rest of lines that are not the 11 or 13. If the files are numerous or very large, this can take some time.
You can also take just the lines 11 and 13 via findstr commands, but anyway the execution of a couple of findstr commands connected via a pipe also takes some time.
You must be aware that any variable that takes its value inside a compound command (like for or if) must be accessed using !delayedExpansion! instead of %standardExpansion%. There are a lot of questions/answers in this site about this point.
My solution below takes a different approach: it reads just the first 13 lines of each file via a redirection instead of for /F command or findstr. If the files are few and small, this method would be similar in time to the other ones. However, I think this method is simpler and easier to understand.
#echo off
setlocal EnableDelayedExpansion
rem Read every *rprt.txt file in this folder
for %%f in (*rprt.txt) do (
rem Read line 11 and 13 of this file via a redirection
< "%%f" (
rem Skip first 10 lines
for /L %%i in (1,1,10) do set /P "dummy="
rem Read line 11 and line 13
set /P "line11="
set /P "dummy="
set /P "line13="
)
rem Get the number in line 11 and compare it
for /F "tokens=5" %%i in ("!line11!") do set "num=%%i"
if 6000 lss !num! if !num! lss 14000 (
rem Get the number in line 13 and compare it
for /F "tokens=5" %%i in ("!line13!") do set "num=%%i"
if !num! gtr 600 copy "%%f" anotherFolder
)
)

Windows Batch renaming from text document

I made a Batch script to rename a large amount of files. It takes their name and searches for it in a text document, copies the line and takes the data I need from it and then renames the file.
It seems to work fine for the most part, but I can't check to see how it's doing because it is constantly producing errors/warnings in the console.
#echo off
set ogg=.ogg
Setlocal EnableDelayedExpansion
for %%a in (*.ogg) do (
set fileNameFull=%%a
set fileName=!fileNameFull:~0,-4!
for /F "delims=" %%a in ('findstr /I !fileName! strings.txt') do (
endlocal
set "stringLine=%%a%ogg%"
)
Setlocal EnableDelayedExpansion
set fullString=!stringLine:~26!
ren %%a "!fullString!"
)
pause
The code works, I'd just like to be able to track progress, as 10,000s of files are being renamed at a time and I've no indication of how far along the process is.
The errors are:
"FINDSTR: Cannot open [...]"
"The syntax of the command is incorrect."
#echo off
Setlocal EnableDelayedExpansion
for %%a in (*.ogg) do (
for /F "delims=" %%q in ('findstr /I /L /c:"%%~na" strings.txt') do (
set "stringLine=%%q"
)
ECHO ren "%%a" "!stringLine:~26!.ogg"
)
pause
This code should be equivalent, but fixed, to the code you've posted.
Fixes:
Removed the endlocal/setlocal complication - not required
changed the inner `for` metavariable - must not be duplicate `%%a`
Changed the `findstr` switches - add `/L` for literal and `/c:` to force single token in case of a separator-in-name; use `%%~na` to specify "the name part of `%%a`" to avoid the substringing gymnastics.
removed said gymnastics
Removed 2-stage string manipulation of destination filename
Removed superfluous setting of `ogg`
The resultant code should duplicate what you have originally, except that it will simply report the rename instruction. You should test this against a small representative sample to verify.
for counting/progress:
set /a count=0
for %%a in (*.ogg) do (
for /F "delims=" %%q in ('findstr /I /L /c:"%%~na" strings.txt') do (
set "stringLine=%%q"
)
ECHO ren "%%a" "!stringLine:~26!.ogg"
set /a count +=1
set /a stringline= count %% 1000
if %stringline% equ 0 echo !count! Processed
)
pause
which should show you progress each 1000.
You could use
if %stringline% equ 0 echo !count! Processed&pause
to wait for user-action before progressing...
BTW -I'm making the assumption that the newname is from column 27+ in your file, since you've not shown us a sample.Also, you should be aware that a simple findstr would locate the target string as a substring anywhere within the file - either as the newname or the oldname. If you invoke the /B switch on the findstr, then the string will match at the very beginning of the line only.

Second latest folder in a Directory

I want a batch file which will find out which is the second latest folder created/modified in a directory.
I found this article but no matter how much i tried i could not understand how it works
#echo off
set "root_dir=c:\somewhere"
pushd "%root_dir%"
set "bl1="
set "bl2="
setlocal enableDelayedExpansion
for /f "tokens=* delims=" %%# in ('dir /b /a:-d /o:d') do (
set "bl2=!bl1!"
set "bl1=%%#"
)
echo %bl2%
endlocal
If i use it as it is then i can get the second latest folder but this script is supposedly able to get which ever latest folder you need , be it 1st or nth.
Could someone please tell me what modifications need to be done to the script to accomplish that. Also how exactly this script works
In your approach, the latest folder is already available in variable bl1; add echo %bl1% at the end before endlocal to display it. Retrieving the nth folder is simply not possible in a flexible way with that script as you would need to define another variable (say bl3, bl4,..., bln) within the loop.
However, you could reverse the sort order of the output of the dir command by changing the /O option, so it returns the latest (most recent) item first. Then let an index number count the iterations of the loop, and if that index equals the predefined number n, store the currently iterated item:
#echo off
setlocal EnableDelayedExpansion
rem // Define N here to get Nth-latest folder:
set /A LATEST=2
set /A INDEX=0
for /F "eol=| delims=" %%# in ('dir /B /A:D /O:-D "C:\somewhere"') do (
set /A INDEX+=1
if !INDEX! EQU !LATEST! (
set "ITEM=%%#"
)
)
if defined ITEM echo %LATEST%th-latest folder: %ITEM%
endlocal
exit /B
Update
Here is a modified script with the following improvements:
Exclamation marks ! in folder names are no longer lost due to toggling delayed expansion;
the target directory can be provided as the first command line argument; if omitted, the current directory is used;
the number n can be given as the second command line argument; if omitted, the user is prompted for it (this addresses elzooilogico's comment); n defaults to 1 for empty input;
the display output is improved to avoid something weird like 1th-latest, 2th-latest and 3th-latest; instead, The latest, 2nd-latest and 3rd-latest is returned, respectively;
So this is the code:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
rem /* define location path and folder pattern as 1st command line argument;
rem /* Define number N as 2nd command line argument to get Nth-latest folder. */
set "LATEST=%~2"
set /A LATEST+=0
if %LATEST% LEQ 0 (set /P LATEST="Enter N [1]: " & set /A LATEST+=0)
if %LATEST% LEQ 0 set /A LATEST=1
set /A INDEX=0
for /F "eol=| delims=" %%# in ('dir /B /A:D /O:-D "%~1"') do (
set /A INDEX+=1
setlocal EnableDelayedExpansion
if !INDEX! EQU !LATEST! (
endlocal
set "ITEM=%%#"
goto :SKIP & rem // break loop after having retrieved Nth-latest folder;
) else endlocal
)
:SKIP
setlocal EnableDelayedExpansion
if defined ITEM (
if %LATEST% EQU 1 (echo The latest file: !ITEM!) else (
if %LATEST% EQU 2 (echo 2nd-latest file: !ITEM!) else (
if %LATEST% EQU 3 (echo 3rd-latest file: !ITEM!) else (
echo %LATEST%th-latest file: !ITEM!)))
)
endlocal
endlocal
exit /B
To achieve a similar result as with the simple script on top of this answer, you need to call this script by the following command line, supposing it has been saved as Nth-latest.bat:
Nth-latest.bat "C:\somewhere" 2

How to display a window of lines in a .txt file in batch?

So I'm building a messaging program in batch (I know, it's newbish) and the program takes user input, puts it in my .txt file log.txt, and types it on the screen. I want the output to look like this...
Title
----------------------
contents
of
the
file
here
----------------------
User input here>>
This may seem simple, but the file will be constantly updated by users and I want the program to only display a range of lines to keep that message area stays the same size. I found a simple program to display specific lines, but I can't make them move down one line each time log.txt is changed. Here it is:
#setlocal enableextensions enabledelayedexpansion
#echo off
set lines=1
set curr=1
for /f "delims=" %%a in ('type bob.txt') do (
for %%b in (!lines!) do (
if !curr!==%%b echo %%a
)
set /a "curr = curr + 1"
)
endlocal
(By the way, this program is called lines.bat. I just call it in cmd to test it.)
To return a defined number of lines starting from a certain line number, you can do the following:
#echo off
setlocal EnableExtensions
rem define the (path to the) text file here:
set "TEXT_FILE=log.txt"
rem define the line number here:
set /A "LINE_NUMBER=1"
rem define the number of lines here:
set /A "LINE_COUNT=5"
set /A "LINE_LIMIT=LINE_NUMBER+LINE_COUNT-1"
for /F delims^=^ eol^= %%L in ('findstr /N /R "^" "%TEXT_FILE%"') do (
setlocal DisableDelayedExpansion
set "LINE=%%L"
setlocal EnableDelayedExpansion
for /F "tokens=1 delims=:" %%N in ("!LINE!") do set "LNUM=%%N"
set "LINE=!LINE:*:=!"
if !LNUM! GEQ !LINE_NUMBER! (
if !LNUM! LEQ !LINE_LIMIT! (
echo !LINE!
)
)
endlocal
endlocal
)
endlocal
The findstr command with the /R "^" search pattern returns all lines. The findstr switch /N lets every line precede with a line number (starting from 1) and a colon. The : is used to split the line in two parts: the first part representing the line number is checked whether it is in the range to be returned; the second part is the original line of text which is simply output in case. Even empty lines are taken into account.
You might ask why not simply using the above mentioned : as a delims delimiter option for for /F, but this would cause problems with lines of text starting with :.
The toggling of delayed expansion is necessary to avoid trouble with special characters like !, for instance.
To return the last defined number of lines, the following approach can be used:
#echo off
setlocal EnableExtensions
rem define the (path to the) text file here:
set "TEXT_FILE=log.txt"
rem define the number of lines here:
set /A "LINE_COUNT=5"
for /F "tokens=1 delims=:" %%L in ('findstr /N /R "^" "%TEXT_FILE%"') do (
set /A "LINE_SKIP=%%L"
)
set /A "LINE_SKIP-=LINE_COUNT"
if %LINE_SKIP% GTR 0 (
set "LINE_SKIP=skip^=%LINE_SKIP%^ "
) else (
set "LINE_SKIP="
)
for /F %LINE_SKIP%delims^=^ eol^= %%L in ('findstr /N /R "^" "%TEXT_FILE%"') do (
setlocal DisableDelayedExpansion
set "LINE=%%L"
setlocal EnableDelayedExpansion
set "LINE=!LINE:*:=!"
echo !LINE!
endlocal
endlocal
)
endlocal
Again, the findstr /N /R "^" command is used. But here, we have an additional for /F loop first, which merely counts the number of lines in the text file, extracting the line number preceded by findstr. The second for /F loop is quite similar to the above approach, but a dynamic skip option is introduced, so that the loop starts iterating through the last lines only; the rest is almost the same as above, except that the conditions concerning the current line number have been removed.
I know I could do the counting of lines also by using find /C /V "" rather than looping through the findstr /N /R "^" output, but if there are one or more empty lines at the end of the file, find returns a number one less as the findstr method, so I went for findstr consistently.
Also here, delayed expansion is toggled to avoid trouble with the ! character.

Using FOR loop to copy code between to labels in batch file

Ok so I write in batch files a lot. A while back I asked a question user:cmd on how to copy one part of a running batch file into a new batch file,
Well it works if your going to use it one time in a batch file. My goal is to create multiple large batch files from within a single setup batch. What happens is if they choose to install, then the batch file runs the following.
cls
setlocal EnableDelayedExpansion
color e
::Start of embedded code
set Begin=
for /F "delims=:" %%a in ('findstr /N "^:EMBEDDED_CODE" "%~F0"') do (
if not defined Begin (
set Begin=%%a
) else (
set End=%%a
)
)
::*****************************************************************************
(for /F "skip=%Begin% tokens=1* delims=[]" %%a in ('find /N /V "" "%~F0"') do (
if %%a equ %End% goto :Build-file2
echo(%%b
)) > file1.bat & goto :Build-file2
)
goto :Build-file2
:EMBEDDED_CODE Begin
CODE TO PUT INTO "file1.bat"
:EMBEDDED_CODE End
:Build-file2
cls
setlocal EnableDelayedExpansion
color e
::Start of embedded code
set Begin=
for /F "delims=:" %%a in ('findstr /N "^:EMBEDDED_CODE" "%~F0"') do (
if not defined Begin (
set Begin=%%a
) else (
set End=%%a
)
)
::*****************************************************************************
(for /F "skip=%Begin% tokens=1* delims=[]" %%a in ('find /N /V "" "%~F0"') do (
if %%a equ %End% goto :EOF
echo(%%b
)) > file2.bat & goto :EOF
)
goto :EOF
:EMBEDDED_CODE Begin
CODE TO PUT INTO "file2.bat"
:EMBEDDED_CODE End
The problem that is occurring is instead of it just copying the code between labels EMBEDDED_CODE Begin and EMBEDDED_CODE End in the first FOR loop it copies from EMBEDDED_CODE Begin down to the very bottom of the script puts it in the file I want and then goes to the next FOR loop which repeats the process with different code between the to labels. so file1.bat and file2.bat both contain the exact same code but with the desired file names of file1.bat AND file2.bat.
Why would you expect anything different than the results you are getting? The FINDSTR will search the entire file, so Begin is set to the first occurrence of :EMBEDDED_CODE in the first block of code, and End is set to the last occurrence in the last block of code (last value set wins). You replicate the code, so of course you get the same faulty result two times.
Simply change the labels in your second block of code, perhaps :EMBEDDED_CODE2, and adjust your 2nd FINDSTR accordingly. All should work then.
I often use a slightly different approach that minimizes the amount of file reading. Simply modify all lines from a given embedded block of code with the same unique prefix. Then FINDSTR can directly output the desired lines, and a FOR /F is used to strip off the prefix. You just need the prefix to end with a character that never matches the beginning of your code.
You should be careful about enabling delayed expansion when reading a file with FOR /F. Your embedded code will be corrupted if it contains ! and delayed expansion is enabled. (unless the ! is escaped, but that can be a pain)
#echo off
for %%C in (1 2) do (
for /f "tokens=1* delims=}" %%A in ('findstr /bl ":%%C}" "%~f0"') do echo(%%B
)>file%%C.bat
:1}Your first code block goes here
:1}
:1} Blank lines and indents are preserved
:1}And so are exclamation points!
:2}And here is your second code block
:2}...
echo file1.bat
echo ---------
type file1.bat
echo(
echo(
echo file2.bat
echo ---------
type file2.bat
This will almost do what you need.
This code needs to read twice the input file, first to locate the range of lines to process (findstr line numbering), and second to extract them. In second loop findstr numbering is used again to avoid for /f to compress blank lines and alter line numbering.
On the other hand, the problem with special characters inside extacted text is handled, enabling and disabling delayed expansion as needed.
Maybe not the best performance, but it seems to work. Adapt as needed.
#echo off
setlocal enableextensions enabledelayedexpansion
call :extractEmbedded "Section1" extracted.txt
if not errorlevel 1 (
cls
type extracted.txt
)
exit /b
:extractEmbedded id outputFile
rem prepare environment
setlocal enableextensions enabledelayedexpansion
rem asume failure on execution
set "_return=1"
rem find embedded zone in current file
set "_start="
set "_end="
for /f "tokens=1 delims=:" %%l in ('findstr /n /b /c:":EMBEDDED %~1" "%~f0"') do (
if not defined _start ( set "_start=%%l" ) else ( set "_end=%%l" )
)
rem adjust lines to process
set /a "_start+=0"
set /a "_end-=1"
rem if nothing found, task done
if %_start% GEQ %_end% goto endExtractEmbedded
rem prepare file extraction
if "%_start%"=="0" (set "_skip=" ) else ( set "_skip=skip^=%_start%" )
rem extract proper area of file to output file
(for /f tokens^=^*^ %_skip%^ eol^= %%l in ('findstr /n "^" "%~f0"') do if !_start! LSS !_end! (
setlocal disabledelayedexpansion
set "_line=%%l"
setlocal enabledelayedexpansion
echo(!_line:*:=!
endlocal & endlocal
set /a "_start+=1"
))>"%~2"
rem everything ok
set "_return=0"
:endExtractEmbedded
rem exit with errorlevel
endlocal & exit /b %_return%
:EMBEDDED Section1
This is a section; of embedded!!! code
that needs to be extracted to generate
a new file to be processed.
TEST: !""$%&/()=?¿^*[];,:-\|
:EMBEDDED Section1

Resources