Home:ALL Converter>Count the number of newlines (both Unix and Windows)

Count the number of newlines (both Unix and Windows)

Ask Time:2019-04-17T19:31:49         Author:jotasi

Json Formatter

I have a text file and want to write a batch file to verify that it only contains one line with a specific content without any newline at the end of said line.

Comparing the content of the line is not difficult, as I can just read it into a variable and then compare it to what I expect.

My problem is with asserting that there are no superfluous newlines around. As long as there are only Windows line endings (CRLF), I can do this quite easily by counting the number of lines ending with a newline, similarly to here:

Set num_of_endlines=0
For /f "tokens=1 delims=:" %%i in ('FINDSTR /r /n "$" %filepath%') DO (
    Set num_of_endlines=%%i
)

If that num_of_endlines is 0 then all is good.

My problem is now, that this method does not work for Unix line endings. I also tried counting the line starts ("^") instead of the line endings ("$"). That improved the result as now leading newlines are captured, regardless whether they are CRLF or LF. But this does not capture a newline at the end of the first line (Not even a CRLF). Is there any way to count the number of CRLF and LF in a text file using a batch file?

Author:jotasi,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/55726596/count-the-number-of-newlines-both-unix-and-windows
lit :

Windows FINDSTR is not fully regex capable. But, PowerShell can do it. Note the use of -Raw to get the contents of the file. That is required to see the newline bytes.\n\nSET \"THEFILE=t.bash\"\n\nFOR /F %%a IN ('powershell -NoLogo -NoProfile -Command ^\n \"(Get-Content -Path '%THEFILE%' -Raw | Select-String -Pattern '\\x0a|\\x0d' | Measure-Object).Count\"') DO (\n SET \"LINECOUNT=%%a\"\n)\n\nECHO LINECOUNT is %LINECOUNT%\n",
2019-04-17T12:20:17
yy