Home Some Windows magic
Post
Cancel

Some Windows magic

Script to get number of lines in a file:

REM %1 is the file name to be parsed, passed at command line

@set count=0
for /f %%a in (%1) do (
@set /a count+=1
)

@echo %count%


Script that will look at each entry (no spaces) in a file (called seq_no_t3.csv in my example) and search for lines that have an exact match with the string (ie "^string$") in a list of files (specified by adroms*_replies.txt in my example) and output the string "string,file_name" followed by an extra \n in an output file (called loc_matches_2.txt in my example). Also, it will constantly echo to the screen the line number on which it is currently working on from input file.

@echo off
@setlocal

set count=0
for /f %%i in ('type .\seq_no_t3.csv') do (
set /a count+=1
set count
<nul (set /p tmp=%%i) >> loc_matches_2.txt
<nul (set /p tmp=,) >> loc_matches_2.txt
for /f %%j in (\findstr /m /r "^%%i$" adroms*_replies.txt') do (
<nul (set /p tmp=%%j) >> loc_matches_2.txt
)
@echo. >> loc_matches_2.txt
)

@endlocal
@echo on


This script has several interesting things going on. Apart from the use of the relatively powerful for loop (where in this case the default delimiter of or is being used), the lines starting with will pipe a nul response to set /p so that the variable remains unchanged. Due to the quirky way set works, set /p prints the value to the right of the equals sign, not the value of the variable itself. Therefore, you're not changing the value of the %tmp% variable yet you are appending %%i/,/%%j to the file with no CRLF! (see source).

Pending fixes:
1.- Fix issue where blank lines (actually they have space characters) are printed to output file
2.- Fix issue where if the input string is matched in several files, a list of files (where delim=CRLF) is appended to the line corresponding to the input string. Hence there will be lines with no comma separation - instead they will have a file name where the last input string was found.

This post is licensed under CC BY 4.0 by the author.

Vim column mode

Vim Tip of the Day