I had a nifty trick in Windows cmd.exe
(at least up to XP) to emulate the behaviour of the UNIX echo without a newline, echo -n
. For example, the command:
<nul: set /p junk= xyzzy
would result in exactly six characters being output, the leading space and the string "xyzzy", and nothing else.
If you're interested in why this works, it's actually an input command which outputs
" xyzzy"
as the prompt then waits for user input before assigning that input to thejunk
environment variable. In this particular case, it doesn't wait for user input since it grabs the input from thenul
device.
It was rather useful in cmd
scripts when (for example) processing files in a loop (one iteration per file) where you want to list more than one per line. By using this trick, you could simply output each file name followed by a space and no newline then, after the loop, output a newline to finish up:
Processing files:
file1.txt file42.txt p0rn.zip
Now I discover that, under Windows 7, the spaces are no longer output so what I get is:
Processing files:
file1.txtfile42.txtp0rn.zip
Is there a way I can get set /p
to start honouring my spaces again, or is there another way in Win7 to achieve the same effect?
I've tried quoting, using .
(which works in echo
) and even escaping the string with ^
, but none of them seem to work:
C:\Pax> <nul: set /p junk= xyzzy
xyzzy
C:\Pax> <nul: set /p junk=" xyzzy"
xyzzy
C:\Pax> <nul: set /p junk=' xyzzy'
' xyzzy'
C:\Pax> <nul: set /p junk=. xyzzy
. xyzzy
C:\Pax> <nul: set /p junk=^ xyzzy
xyzzy
What I need is:
C:\Pax> some_magical_command_with_an_argument xyzzy
xyzzy
which will give me the space(s) at the start and no newline at the end.
You mean like this?
Result:
item 1 item 2 item 3 item 4
Or do you absolutely insist on a space at the start?
OK, have the right answer now: you can't have a leading
<space>
in Win7 withset /p
. There are differences between Windows versions:source
For an other technique to get leading spaces in pure batch see here
This isn't using
set
or othercmd
-internal stuff, but you can usecscript
(also included in a standard Windows install) to do a similar thing. You can even control it from thecmd
file itself (no separate files to maintain) by use of creating temporaryvbs
files.Place this code in your
cmd
file:The output of this is what you would expect:
This is very similar to paxdiablo's answer, except I use a hybrid JScript/batch file instead of a temporary VBScript file.
My script is called
jEval.bat
- and it simply evaluates any valid JScript expression and writes the result to stdout, optionally with a trailing newline. The silly little script is extremely useful for batch programming.Assuming
jEval.bat
is either in your current folder, or somewhere in your PATH, then you can simply do something like:Here is the script. It really is very simple. Most of the code is related to documentation, error handling, and a built in help system.