Windows batch: echo without new line

后端 未结 18 1667
失恋的感觉
失恋的感觉 2020-11-22 04:01

What is the Windows batch equivalent of the Linux shell command echo -n which suppresses the newline at the end of the output?

The idea is to write on t

18条回答
  •  孤城傲影
    2020-11-22 04:55

    DIY cw.exe (console write) utility

    If you don't find it out-of-the-box, off-the-shelf, you can DIY. With this cw utility you can use every kind of characters. At least, I'd like to think so. Please stress-test it and let me know.

    Tools

    All you need is .NET installed, which is very common nowadays.

    Materials

    Some characters typed/copy-pasted.

    Steps

    1. Create .bat file with the following content.
    /* >nul 2>&1
    
    @echo off
    setlocal
    
    set exe=cw
    for /f "tokens=* delims=" %%v in ('dir /b /s /a:-d  /o:-n "%SystemRoot%\Microsoft.NET\Framework\*csc.exe"') do set "csc=%%v"
    
    "%csc%" -nologo -out:"%exe%.exe" "%~f0"
    
    endlocal
    exit /b %errorlevel%
    
    */
    
    using System;
    
    namespace cw {
        class Program {
            static void Main() {
                var exe = Environment.GetCommandLineArgs()[0];
                var rawCmd = Environment.CommandLine;
                var line = rawCmd.Remove(rawCmd.IndexOf(exe),exe.Length).TrimStart('"');
                line = line.Length < 2 ? "\r" : line.Substring(2) ;
                Console.Write(line);
            }
        }
    }
    
    1. Run it.

    2. Now you have a nice 4KB utility so you can delete the .bat.

    Alternatively, you can insert this code as a subroutine in any batch, send the resulting .exe to %temp%, use it in your batch and delete it when you're done.

    How to use

    If you want write something without new line:
    cw Whatever you want, even with "", but remember to escape ^|, ^^, ^&, etc. unless double-quoted, like in "| ^ &".

    If you want a carriage return (going to the beginning of the line), run just
    cw

    So try this from command line:

    for /l %a in (1,1,1000) do @(cw ^|&cw&cw /&cw&cw -&cw&cw \&cw)
    

提交回复
热议问题