Page 1 of 1

strip trailing CR/LF from text file.

Posted: 06 Oct 2016 03:55
by amichaelglg
quite simply is it possible and how am i able to remove a cr/lf code from a text file if it's the last entry in the text file?

Re: strip trailing CR/LF from text file.

Posted: 06 Oct 2016 06:13
by Squashman
You can do it with Dave's JREPL or you could do it with Vbscript as well.

Re: strip trailing CR/LF from text file.

Posted: 06 Oct 2016 06:27
by penpen
A pure batch solution is (slower than the solutions above, but) also possible, if it is acceptable that all line ends are changed to '\r\n' (except the last):

Code: Select all

@echo off
setlocal enableExtensions disableDelayedExpansion

set "inputFile=input.txt"
set "outputFile=output.txt"

:: test if file ends with a '\n' (true only if an additional "\r\n" will add no new line)
for /F "tokens=1* delims=:" %%a in ('findstr /N "^" "%inputFile%"') do set "n=%%a"
for /F "tokens=1* delims=:" %%a in ('^(type "%inputFile%" ^& echo^(^) ^| findstr /N "^" ') do set "m=%%a"
set /A "d=m-n"

:: 'copy' file
(
   set "line="
   if "%d%" == "1" for /F "tokens=1* delims=:" %%a in ('findstr /N "^" "%inputFile%"') do (
      if not "%%~a" == "%n%" (
         echo(%%b
      ) else (
         set line=%%b
         setlocal enableDelayedExpansion
         <nul set /P "=!line!"
         endlocal
      )
   ) else (
      type "%inputFile%"
   )
) > "%outputFile%"

endlocal
goto :eof


penpen

Re: strip trailing CR/LF from text file.

Posted: 06 Oct 2016 08:52
by amichaelglg
thanks.

I only wanted to remove the very last code in the text file.
i.e remove any blank line at the end of the file.

Re: strip trailing CR/LF from text file.

Posted: 06 Oct 2016 08:55
by Squashman
amichaelglg wrote:thanks.

I only wanted to remove the very last code in the text file.
i.e remove any blank line at the end of the file.

Do the files also have blank lines in the middle of the file?

Re: strip trailing CR/LF from text file.

Posted: 06 Oct 2016 09:42
by dbenham
Your requirements are not clear, so I will present solutions to various scenarios, all using JREPL.BAT:

I assume by CR/LF you mean the line terminator. The line terminator may be carriage return, followed by linefeed, or it could simply be a linefeed without a carriage return in front.

1) If you want to remove any line terminator from the last line of the file only

Code: Select all

jrepl "(\r?\n)(?!\s\S)" "" /m /f yourFile.txt /o -


2) If you want to remove all contiguous line terminators that end the file, except for the line terminator on the last non-empty line

Code: Select all

jrepl "(^\r\n|^n)+(?!\s|\S)" "" /m /f yourFile.txt /o -


3) If you want to remove all contiguous line terminators that end the file, including the line terminator on the last non-empty line

Code: Select all

jrepl "(\r?\n)+(?!\s|\S)" "" /m /f yourFile.txt /o -


Dave Benham