How to detect CRLF at the end of file?

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
miskox
Posts: 630
Joined: 28 Jun 2010 03:46

How to detect CRLF at the end of file?

#1 Post by miskox » 19 Jul 2024 09:39

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

Aacini
Expert
Posts: 1914
Joined: 06 Dec 2011 22:15
Location: México City, México
Contact:

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

#2 Post by Aacini » 19 Jul 2024 10:07

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

miskox
Posts: 630
Joined: 28 Jun 2010 03:46

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

#3 Post by miskox » 19 Jul 2024 13:43

That's why I ask you guys! You are genius Antonio!

Thanks!

Saso

Sponge Belly
Posts: 231
Joined: 01 Oct 2012 13:32
Location: Ireland
Contact:

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

#4 Post by Sponge Belly » 19 Jul 2024 15:33

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

miskox
Posts: 630
Joined: 28 Jun 2010 03:46

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

#5 Post by miskox » 20 Jul 2024 07:08

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

Post Reply