Link to home
Start Free TrialLog in
Avatar of Kiran Sonawane
Kiran SonawaneFlag for India

asked on

batch remove <CR><LF> from last line only in text file

I have script which works fine as I expected it  remove <CR><LF> from last line only in text file. But if there is space or tab in record it skips everything. So I want to remove only last line CR CF. Given scripts scans all lines from target text file, removes blank lines (I don't want this. Only scan last line and remove CR CF) and append into destination file.

bcp TRDS.dbo.tbltestExtracts out "C:\Data\CAAGIndividualsFile.TXT" -c -testinstance\T_GSS -Utest -Ptest
call :StripBlankLines CAAGIndividualsFile.TXT

rem del CAAGIndividualsFile.TXT 
rem ren temp_CAAGIndividualsFile.TXT CAAGIndividualsFile.TXT 

goto :eof
:StripBlankLines
For %%x in ("%~1") do set OutF=temp_(%%~nx).txt
if exist "%OutF%" del "%OutF%"
set FirstLine=1
for /F "usebackq delims=" %%B in (%*) do (
	call :TrimWS %%B
	if not "!Line!"=="" (
		if "!FirstLine!"=="1" (
			set FirstLine=0
		) else (
			>>"%OutF%" echo.
		)
		call :write !Line!
	)
)
goto :eof

:TrimWS
set Line=%*
goto :eof 
 
:write
>>"%OutF%"<NUL set /p Dummy=%*
goto :eof           

Open in new window

Avatar of Chris H
Chris H
Flag of United States of America image

ASKER CERTIFIED SOLUTION
Avatar of oBdA
oBdA

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Kiran Sonawane

ASKER

I already tried this. Please try to run the script against attached test file. (comment the bcp line). You will come to know.. Please...
test.txt
@oBdA: Thank you Sir. It seems working... Thank you again  500*4
Avatar of oBdA
oBdA

The issue with that file is that there's a NUL (ASCII 0) in the first line of that file (check it in a hex editor or in something like Notepad++ with "Show all characters" enabled).
This character shouldn't appear in a text file at all, so you need to check your database how it slipped into a text field in the first place and then made its way into an export.
You can expect all kinds of strange behavior when trying to modify a "text" file that contains non-printable characters other than TAB/CR/LF.
The first line looks like actually like this:
Omega Associates, L.L.C[tab]13-3973682[tab][tab]88 Pine Street 31st Floor[tab][NUL][tab][tab][tab][tab][tab][tab][tab][tab][CR][LF]

Open in new window