Search code examples
batch-file

Batch "echo|set/p=" adds a space at the end of the line


Ran into a bit of trouble when using "echo|set/p=" to print lines without carriage return and line feed. Namely that I get an unwanted space at the end of the text I create and I haven't found a way to remove it.

Example: Running echo TEST>>TEST.TXT in batch command line gives a file which contains TEST followed by a carriage return and a line feed.

Running echo|set/p=TEST>>TEST.TXT in batch command line gives a file which contains TEST followed by a single space character, but no carriage return or line feed.

Where does this mysterious space come from and is there any way to remove it?


Solution

  • Instead, you should use

    <nul set /p "=Test" >> test.txt
    

    The differences are:

    • <nul instead of echo | nul simply is an empty redirect, but ECHO with a pipe creates two new cmd.exe instances
    • Using a pipe creates some magic reorder of commands on both sides
    • Use quotes to avoid unwanted spaces or problems with special characters