Search code examples
batch-fileecholinefeed

Echo text with Unix line endings from a Windows batch (.bat) script


Say I have the following batch script:

For ... DO (
SET VAL=%%B
IF defined VAL echo %%A=%%B >> %OUTPUT_FILEPATH%
)

How could I get the echo to output using Unix (just line feed) line endings?

Alternatively, could I write the file as-is then convert it from the batch script afterwards? (some kind of find /r/n and replace with /n? If so, how would I do that?)

I'd like a self-contained solution (i.e. one that doesn't involve downloading extra utilities, and can be done from within the batch script itself [Windows 7]).


Solution

  • Taken from Macros with parameters appended:

    Formatting is tricky, but try

    set ^"LF=^
    
    ^" Don't remove previous line & rem line feed (newline)
    set ^"\n=^^^%LF%%LF%^%LF%%LF%^^"& rem Define newline with line continuation
    
    For ... DO (
    SET VAL=%%B
    IF defined VAL <nul set/P^=%%A=%%B%\n%>> %OUTPUT_FILEPATH%
    )
    

    Or, to avoid the leading space after first line:

    <nul set/P^=%%A=%%B%\n%^>> %OUTPUT_FILEPATH%