Line Counting prob no carrige return Line Fe

Microsoft Windows xp professional w/serv...
May 27, 2010 at 13:14:40
Specs: Windows XP, 256
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 feed

test2.txt has in it
1
2
3 no carriage return and line feed


See More: Line Counting prob no carrige return Line Fe

Report •


#1
May 27, 2010 at 14:21:15
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 felicity

M2


Report •

#2
May 27, 2010 at 15:27:30
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 2

which 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


Report •

#3
May 28, 2010 at 05:40:18
Superb Klint, many thanks to you. This works like a champ!

Report •

Related Solutions


Ask Question