简体   繁体   中英

Count the number of newlines (both Unix and Windows)

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?

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.

SET "THEFILE=t.bash"

FOR /F %%a IN ('powershell -NoLogo -NoProfile -Command ^
    "(Get-Content -Path '%THEFILE%' -Raw | Select-String -Pattern '\x0a|\x0d' | Measure-Object).Count"') DO (
    SET "LINECOUNT=%%a"
)

ECHO LINECOUNT is %LINECOUNT%

If all you want to do is verify that the file does not have any newlines, then

(type "%filepath%" & echo x) | findstr /n "^" | findstr "^2:" >nul && (
  echo FAIL: The file has at least one newline
) || (
  echo SUCCESS: The file does not have any newlines
)

If you need to actually count the number of newlines, then

for /f %%N in (
 '(type "%filepath%" ^& echo x^) ^| findstr /n "^" ^| find /c /v ""'
) do set /a cnt=%%N-1

Or you can let FINDSTR search directly for the newlines!

If you need to verify the file has no newlines

@echo off
setlocal enableDelayedExpansion

set "filepath=...."

(set LF=^
%= This defines a newline variable =%
)

findstr "!LF!" "%filepath%" && (
  echo FAIL: The file contains at least one newline
) || (
  echo SUCCESS: The file does not contain any newlines
)

Or to count the number of newlines

@echo off
setlocal disableDelayedExpansion

set "filepath=...."

(set LF=^
%= This defines a newline variable =%
)

for /f %%N in (
  'cmd /v:on /c findstr "!LF!" "%filepath%" ^| find /c /v ""'
) do set "cnt=%%N"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM