Write HEX values to file in Windows batch
In Linux we can do
to write HEX values to a file.
How can this be done simply in Windows batch?
2 Answers 2
I am assuming you want the ability to write all possible binary bytes in the range \x00 through \xFF. Unfortunately, pure batch does not provide a simple mechanism to do this.
But there are a number of options that are not too difficult.
Undocumented !=ExitCodeASCII! dynamic variable
The !=ExitCodeASCII! dynamic variable reports the ASCII value of the return code of the most recently run external command. But it is limited to ASCII codes from \x20 through \x7E.
I use delayed expansion so that I don’t have to worry about poison characters.
The simplest mechanism to return a specific error code is to use cmd /c exit N , where N must be a decimal value. If you want to pass in a hex value, then the value must first be converted to decimal.
Windows batch uses 0xNN notation to specify a hex value. As others have noted, you can use set /a val=0x66 to do the conversion. Another option is to use for /l %%N in (0x66 1 0x66) do . , the advantage being you don’t need to define an intermediate environment variable to hold the value.
- Must build string one character at a time
- Range limited to 0x20 — 0x7E
FORFILES
The FORFILES command supports 0xNN syntax, so it can generate most characters. But the string must pass through CMD /C, so it cannot be used to generate \0x00, \0x0A, or \0x0D. (I haven’t tested, but I believe all other values work, provided poison characters are appropriately quoted or escaped)
- Pure batch
- Can process an entire string in one pass
- No native XP support
- No support for 0x00, 0x0A, or 0x0D
- Escaping / quoting of poison characters can be tricky
CERTUTIL
The CERTUTIL supports a -decodeHex verb that can read hex values and write directly to a file
- Pure batch
- All possible bytes codes supported
- Absolute control of newlines and carriage returns
- Can process an entire string (or file!) in one pass
- Fast
- Requires a temp file
Hybrid JScript / batch — simple solution
It is very easy to embed and execute JScript within a batch script. And JScript has native ability to interpret many escape sequences, including \xNN. However, the \xNN escape sequences actually map to Unicode code points, so some of the high order byte codes do not map to the correct character values. And the results for high order bytes can vary depending on your machines default character set.
Below I define a :jWrite subroutine that can write lines with embedded escape sequences. Simply change the WriteLine to Write in the JScript code if you want to write strings without the newline characters.
- Pure script that runs natively on all Windows machines from XP onward
- Very simple JScript code
- Can process entire strings in one pass
- Many other escape sequences available, such as \\ , \t , \r , \n , etc.
- Easy to mix ordinary text with escape sequences, but double quote must be \x22
- Not all high order bytes give the correct result
- Results are dependent on your machine’s default character set. Best if Windows 1252
Hybrid JScript / batch — more robust, but complex solution
It is not too difficult to write some JScript code to properly interpret all \xNN codes to give the correct byte as long as your machine defaults to Windows-1252. And if your command session’s active code page also matches Windows 1252, then you can freely mix in normal text.
- Pure script that runs natively on all Windows machines from XP onward
- Can process entire strings in one pass
- All bytes codes from \x00 through \xFF are supported
- Many other escape sequences available, such as \\ , \t , \r , \n , etc.
- Easy to mix ordinary text with escape sequences, but double quote must be \x22
- Only gives correct results for all bytes if your machine defaults to Windows-1252
- Moderately complex JScript code
JREPL.BAT — Hybrid JScript/batch regular expression text processing utility
My JREPL.BAT utility was originally designed to perform regular expression search and replace operations on text files. But it has options that allow it to easily write strings with embedded escape sequences, and it can give the correct result for all byte codes no matter what default character set your machine uses.
If your machine defaults to any single byte character set, then you can safely use the following with all possible escape sequences from \x00 through \xFF, and you can freely mix in normal text along with escape sequences.
The /s «=» option specifies an undefined environment variable as the input source, which is interpreted as an empty string. The first $ argument matches the end of the empty string. The second «\x66\x6f\x6f» argument specifies the replacement value. The /x option enables escape sequences within the replacement string, and the /o test.txt option specifies the output file.
If you want to append to test.txt, then add the /APP option.
If you want \n end-of-line instead of \r\n, (Unix style instead of Windows) then add the /U option
If you don’t want any new line terminators, then add the /M option.
Lastly, if your machine does not default to a single byte character set, you can still force the correct result for all escape sequences by specifying a single byte character set like Windows-1252 for the output format. However, if the specified character set does not match your command session’s active code page, then only escape sequences are guaranteed to work — some normal text characters may give the wrong result.
- Pure script that runs on any Windows machine from XP onward
- Can process entire strings in one pass
- All bytes codes from \x00 through \xFF are supported
- Many other escape sequences available, such as \\ , \t , \r , \n , etc.
- Easy to mix ordinary text with escape sequences, but double quote must be \x22 or \q
- Default character set agnostic — can always give the correct result
- Once you have JREPL in your arsenal of tools, you will find many uses for it. It is a powerful tool.
- Requires download of a 3rd party script
How do I echo and send console output to a file in a bat script?
I have a batch script that executes a task and sends the output to a text file. Is there a way to have the output show on the console window as well?
Is there a way to have the output of dir display in the console window as well as put it into the text file?
12 Answers 12
No, you can’t with pure redirection.
But with some tricks (like tee.bat) you can.
I try to explain the redirection a bit.
You redirect one of the ten streams with > file or , this means the stream 1 (STDOUT) will be redirected.
So you can redirect any stream with prepending the number like 2> err.txt and it is also allowed to redirect multiple streams in one line.
In this example the «standard output» will go into files.txt, all errors will be in err.txt and the stream3 will go into nothing.txt (DIR doesn’t use the stream 3).
Stream0 is STDIN
Stream1 is STDOUT
Stream2 is STDERR
Stream3-9 are not used
But what happens if you try to redirect the same stream multiple times?
«There can be only one», and it is always the last one!
So it is equal to dir > two.txt
Ok, there is one extra possibility, redirecting a stream to another stream.
2>&1 redirects stream2 to stream1 and 1>files.txt redirects all to files.txt.
The order is important here!
are different. The first one redirects all (STDOUT and STDERR) to NUL,
but the second line redirects the STDOUT to NUL and STDERR to the «empty» STDOUT.
As one conclusion, it is obvious why the examples of Otávio Décio and andynormancx can’t work.
Both try to redirect stream1 two times, but «There can be only one», and it’s always the last one.
So you get
And in the first sample redirecting of stream1 to stream1 is not allowed (and not very useful).
How to create empty text file from a batch file?
Can somebody remember what was the command to create an empty file in MSDOS using BAT file?
13 Answers 13
DOS has a few special files (devices, actually) that exist in every directory, NUL being the equivalent of UNIX’s /dev/null : it’s a magic file that’s always empty and throws away anything you write to it. Here’s a list of some others; CON is occasionally useful as well.
To avoid having any output at all, you can use
/y prevents copy from asking a question you can’t see when output goes to NUL .
After reading the previous two posts, this blend of the two is what I came up with. It seems a little cleaner. There is no need to worry about redirecting the «1 file(s) copied.» message to NUL , like the previous post does, and it looks nice next to the ECHO OutputLineFromLoop >> Emptyfile.txt that will usually follow in a batch file.
Techniques I gathered from other answers:
Makes a 0 byte file a very clear, backward-compatible way:
idea via: anonymous, Danny Backett, possibly others, myself inspired by JdeBP’s work
A 0 byte file another way, it’s backward-compatible-looking:
A 0 byte file 3rd way backward-compatible-looking, too:
A 0 byte file the systematic way probably available since Windows 2000:
A 0 bytes file overwriting readonly files
A single newline (2 bytes: 0x0D 0x0A in hex notation, alternatively written as \r\n ):
Note: no space between echo , . and > .
edit It seems that any invalid command redirected to a file would create an empty file. heh, a feature! compatibility: uknown
A 0 bytes file: invalid command/ with a random name (compatibility: uknown):
via: great source for random by Hung Huynh
edit 2 Andriy M points out the probably most amusing/provoking way to achieve this via invalid command
A 0 bytes file: invalid command/ the funky way (compatibility: unknown)
A 0 bytes file 4th-coming way: