问题
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]).
回答1:
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%
回答2:
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? ;-)
来源:https://stackoverflow.com/questions/40803502/echo-text-with-unix-line-endings-from-a-windows-batch-bat-script