Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]).

like image 785
simonalexander2005 Avatar asked Oct 24 '25 02:10

simonalexander2005


2 Answers

The suitable way to perform this conversion is not via a Batch file, but using another programming language, like JScript; this way, the conversion process is fast and reliable. However, you don't need a hundreds lines program in order to achieve a replacement as simple as this one. The two-lines Batch file below do this conversion:

@set @a=0 /* & cscript //nologo //E:JScript "%~F0" < input.txt > output.txt & goto :EOF */

WScript.Stdout.Write(WScript.Stdin.ReadAll().replace(/\r\n/g,"\n"));

EDIT: I added a modification to the original code that allows to include more commands in the Batch part in the standard way.

@set @a=0 /*

@echo off
set "OUTPUT_FILEPATH=C:\Path\Of\The\File.txt"
cscript //nologo //E:JScript "%~F0" < "%OUTPUT_FILEPATH%" > output.txt
move /Y output.txt "%OUTPUT_FILEPATH%"

goto :EOF */

WScript.Stdout.Write(WScript.Stdin.ReadAll().replace(/\r\n/g,"\n"));

The first line is a trick that hide the cscript command from the JScript code, so the compilation of this hybrid .BAT file don't issue errors.

In the JScript code: WScript.Stdin.ReadAll() read the whole redirected input file; this may cause problems if the file is huge. The replace method use a regex to identify the text to replace and put in its place the second string; you may read a further description of this topic at this link. The WScript.Stdout.Write just take the output from replace and send it to the screen. Easy! Isn't it? ;-)

like image 146
Aacini Avatar answered Oct 25 '25 15:10

Aacini


If you are OK with using PowerShell, you can produce a Unix newline like this:

PowerShell -Command Write-Host

You can combine this with the SET /P trick to output text without newlines and add newlines manually. For example:

( ECHO | SET /P="Hello World!" & PowerShell -Command Write-Host ) > output.txt

After this, output.txt will contain the text Hello World! with a single 0x0a character appended.

like image 26
Matus Horvath Avatar answered Oct 25 '25 16:10

Matus Horvath



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!