Friday, October 15, 2010

Removing carriage returns from a text file using a DOS batch file



Hello there. Well this is really a test post more than anything else to get me aquainted with the SyntaxHighlighter set of files for code publishing on a blog available at alexgorbatchev.com. But in doing so I thought I would give an example of how to remove CR/LF characters from a text file using only batch commands.

The only trick to this is to note that when doing string manipulations in DOS, the enabledelayedepansion option needs to be set, and the variables then need to be accessed as !VAR! instead of %VAR% when being reused in a FOR loop.

@echo off 
setlocal enabledelayedexpansion

for /f %%j in (%1) do (
  set linea=%%j 
  set line=!line!!linea!
 )
echo !line! > %1

3 comments:

  1. for /f "delims=" %%a in (myfile.txt) do (
    echo/|set /p ="%%a%"
    )>>newfile.txt

    ReplyDelete
    Replies
    1. Thank you. This is perfect.
      It works.

      Delete
  2. Hi,
    I have tried the below script to remove the carriage return from the end of line from a text file.after executing the script it displays only the last record in the file removing the carriage return.
    can anyone help me on this.
    @echo off
    SetLocal DisableDelayedExpansion
    for /f "tokens=*" %%a in ('find /n /v "" ^< "old_file.txt"') do (
    set line=%%a
    SetLocal EnableDelayedExpansion
    set line=!line:*]=!
    rem "set /p" won't take "=" at the start of a line....
    if "!line:~0,1!"=="=" set line= !line!

    rem there must be a blank line after "set /p"
    rem and " "new_file.txt"

    ReplyDelete