I have a batch file and I'm trying to count lines in multiple .txt files. I'm running into a problem where if one of the .txt files does not have a carriage return and line feed the count will be off by one. set /a count1=0
for /f %%A in ('type "*.txt"^|find /c /v "-------------" ') do set count1=%%A
pause
test1.txt has in it
1
2
3 This has a carriage return and line feedtest2.txt has in it
1
2
3 no carriage return and line feed
In DOS & windows the CRLF defines line breaks. Stated another way, if there's no 0d0a there ain't no line.
=====================================
Helping others achieve escape felicityM2
As I understand it, the problem is that the last line of your first
file is not terminated by a CR LF sequence. The file just ends
abruptly. So when you TYPE *.txt this concatenates all the
files, but because the first file doesn't end with a CR LF, the
first line of the second file gets joined to the last line of the
first file. So you get:File 1 line 1
File 1 line 2File 2 line 1
File 2 line 2which is 3 lines, when you are expecting 4.
This is a problem because it is not uncommon for a file's last
line not to end with CR LF, although it is highly advisable.One possible workaround is to count the lines file-by-file:
set /a count1=0
for %%A in (*.txt) do (
for /f %%B in ('find /c /v "" ^< %%A') do set /a count1 += %%B
)
echo %count1%
pause
Superb Klint, many thanks to you. This works like a champ!
Yes (14) | ![]() | |
No (14) | ![]() | |
I don't know (15) | ![]() |