Page 1 of 1

How to detect CRLF at the end of file?

Posted: 19 Jul 2024 09:39
by miskox
What would be the easiest way to check if a .txt file has a CRLF at the end? If it is not there CRLF should be added.

For adding CRLF to the end of the file I use:

Code: Select all

@echo off
::Define LF variable containing a linefeed (0x0A)
set LF=^


::Above 2 blank lines are critical - do not remove

::Define CR variable containing a carriage return (0x0D)
for /f %%a in ('copy /Z "%~dpf0" nul') do set "CR=%%a"
echo %cr%%lf%>>file.txt
Thanks.
Saso

Re: How to detect CRLF at the end of file?

Posted: 19 Jul 2024 10:07
by Aacini
This works:

Code: Select all

@echo off
setlocal EnableDelayedExpansion

rem Get the last line and its start position in the file
for /F "tokens=1* delims=:" %%a in ('findstr /O "^" file.txt') do set "start=%%a" & set "line=%%b"

rem Calculate the length of last line assuming it don't ends in CRLF
for %%a in (file.txt) do set /A "len=%%~Za-start-1"

rem If line have this lenght, it does NOT ends in CRLF
if "!line:~%len%!" neq "" echo Last line does NOT ends in CRLF
To add a CRLF to a file, just do this:

Code: Select all

echo/>> file.txt
Your code adds two CRLF pairs = one empty line at end of file

Antonio

Re: How to detect CRLF at the end of file?

Posted: 19 Jul 2024 13:43
by miskox
That's why I ask you guys! You are genius Antonio!

Thanks!

Saso

Re: How to detect CRLF at the end of file?

Posted: 19 Jul 2024 15:33
by Sponge Belly
Hi Saso,

Try this one-liner:

Code: Select all


findStr /v $ file.txt >nul && echo(no CR-LF at EOF || echo(file ends with CR-LF

Only works for CR-LF (Windows) files, and not LF (Unix) files.

HTH! :)

- SB

Re: How to detect CRLF at the end of file?

Posted: 20 Jul 2024 07:08
by miskox
Thank you, SB! Workd great.

So I have (thanku you Aacini and SB):

Code: Select all

findStr /v $ file.txt >nul && echo/>> file.txt
Saso