Batch: delete line feed from end of text file?

Peter picture Peter · Jun 6, 2011 · Viewed 9.3k times · Source

I have a .txt file where I need to get rid of the last line feed. Looking at the file in a HEX Editor it shows "0d 0a" at the end.

I have looked at the thread How to delete Linefeed using batch file but that did not help. I have tried COPY source target /b which also does not help.

Unfortunately I can't use Java or any third party tools, I need to use a batch file.

Does anyone have an idea how to get rid of that line feed at the end?

Thank you very much and best regards, Peter

Answer

PA. picture PA. · Jun 7, 2011

try the following code as an starting point

@echo off
copy %1 temp.txt
echo d >debug.tmp
echo r >>debug.tmp
echo a >>debug.tmp
echo dec cx >>debug.tmp
echo dec cx >>debug.tmp
echo. >>debug.tmp
echo g =100 102 >>debug.tmp
echo w >>debug.tmp
echo q >>debug.tmp
debug temp.txt <debug.tmp

This batch, first, copies the file to a temporary file that needs to have a 8.3 name.

Then it prepares a debug script to chop off the last two bytes of the temporary file.

The first two debug instructions R and D are only to show the contents of the file and the register (with the important CX value that contains the length of the file) They can be removed.

Then the debug script enters assembler mode A and produces two DEC CX instructions, that decrement twice the value of CX. The blank line leaves assembler mode.

The script executes G the two assembly instructions.

Then the debug script writes W back to the file the same contents read, minus two bytes in length. And finally quits Q debug.

This code only works with files smaller than 64kB. For bigger files you need to extend the assembly code, checking for carry flag after decrementing CX to decrement BX.

For more information read DEBUG /? and then try DEBUG and ?