- Command prompt (Cmd. exe) command-line string limitation
- More information
- Examples
- How to work around the limitation
- Strings v2.53
- Introduction
- Using Strings
- Командные строки
- Синтаксис командных строк
- Типы данных для переменных команд
- How to find the number of occurrences of a string in file using windows command line?
- 9 Answers 9
- Base64 Encode “string” — command-line Windows?
- 7 Answers 7
Command prompt (Cmd. exe) command-line string limitation
This article discusses the limitation to the length of the strings that you use from the command prompt in Command Prompt (Cmd.exe). It also provides methods that you can use to work around this limitation.
Original product version: В Windows Server 2012 R2, Windows Server 2008 R2 Service Pack 1, Windows 7 Service Pack 1
Original KB number: В 830473
More information
The maximum length of the string that you can use at the command prompt is 8191 characters.
This limitation applies to:
- the command line
- individual environment variables that are inherited by other processes, such as the PATH variable
- all environment variable expansions
If you use Command Prompt to run batch files, this limitation also applies to batch file processing.
Examples
The following examples show how this limitation applies to commands that you run in Command Prompt, and commands that you use in a batch file.
In Command Prompt, the total length of the following command line can’t contain more than 8191 characters:
In a batch file, the total length of the following command line can’t contain more than 8191 characters:
This limitation applies to command lines that are contained in batch files when you use Command Prompt to run the batch file.
In Command Prompt, the total length of EnvironmentVariable1 after you expand EnvironmentVariable2 and EnvironmentVariable3 can’t contain more than 8191 characters:
In a batch file, the total length of the following command line after you expand the parameters can’t contain more than 8191 characters:
Even though the Win32 limitation for environment variables is 32,767 characters, Command Prompt ignores any environment variables that are inherited from the parent process and are longer than its own limitations of 8191 characters (as appropriate to the operating system). For more information about the SetEnvironmentVariable function, see SetEnvironmentVariableA function.
How to work around the limitation
To work around the limitation, use one or more of the following methods, as appropriate to your situation:
Modify programs that require long command lines so that they use a file that contains the parameter information, and then include the name of the file in the command line.
For example, instead of using the ExecutableFile.exe Parameter1 Parameter2. ParameterN command line in a batch file, modify the program to use a command line that is similar to the following command line, where ParameterFile is a file that contains the required parameters (parameter1 parameter2. ParameterN):
Modify programs that use large environment variables so that the environment variables contain less than 8191 characters.
For example, if the PATH environment variable contains more than 8191 characters, use one or more of the following methods to reduce the number of characters:
- Use shorter names for folders and files.
- Reduce the depth of folder trees.
- Store files in fewer folders so that fewer folders are required in the PATH environment variable.
- Investigate possible methods that you can use to reduce the dependency of PATH for locating .dll files.
—>
Strings v2.53
By Mark Russinovich
Published: July 4, 2016
Download StringsВ (506 KB)
Introduction
Working on NT and Win2K means that executables and object files will many times have embedded UNICODE strings that you cannot easily see with a standard ASCII strings or grep programs. So we decided to roll our own. Strings just scans the file you pass it for UNICODE (or ASCII) strings of a default length of 3 or more UNICODE (or ASCII) characters. Note that it works under Windows 95 as well.
Using Strings
usage:
Strings takes wild-card expressions for file names, and additional command line parameters are defined as follows:
Parameter | Description |
---|---|
-a | Ascii-only search (Unicode and Ascii is default) |
-b | Bytes of file to scan |
-f | File offset at which to start scanning. |
-o | Print offset in file string was located |
-n | Minimum string length (default is 3) |
-s | Recurse subdirectories |
-u | Unicode-only search (Unicode and Ascii is default) |
-nobanner | Do not display the startup banner and copyright message. |
To search one or more files for the presence of a particular string using strings use a command like this:
Download StringsВ (506 KB)
Runs on:
- Client: Windows Vista and higher
- Server: Windows Server 2008 and higher
- Nano Server: 2016 and higher
—>
Командные строки
Чтобы отправить командную строку на устройство MCI, используйте функцию mciSendString , которая включает параметры для команды String и буфер для любых возвращаемых сведений.
Функция mciSendString возвращает нуль в случае успеха. Если функция завершается ошибкой, в слове с низким порядком возвращаемого значения содержится код ошибки. Этот код ошибки можно передать функции мЦижетеррорстринг , чтобы получить текстовое описание ошибки.
Синтаксис командных строк
В строках команд MCI используется единообразный синтаксис модификатора глагола-Object. Каждая Командная строка содержит команду, идентификатор устройства и аргументы команды. Аргументы являются необязательными для некоторых команд и являются обязательными для других.
Командная строка имеет следующий вид:
аргументы идентификатора устройства командной строки _
Эти компоненты содержат следующие сведения:
_ Идентификатор устройства определяет экземпляр драйвера MCI. _ Идентификатор устройства создается при открытии устройства.
Аргументы задают флаги и переменные, используемые командой. Флаги — это ключевые слова, распознаваемые командой MCI. Переменные — это числа или строки, которые применяются к команде или флагу MCI.
Например, команда Play использует аргументы «от позиции » и «to position » для указания позиций, с которых начинается и заканчивается воспроизведение. Вы можете перечислить флаги, используемые командой, в любом порядке. При использовании флага, связанного с переменной, необходимо указать значение для переменной.
Неуказанные (и необязательные) аргументы команды предполагают значение по умолчанию.
Следующий пример функции отправляет команду Play с флагами «from» и «to».
Типы данных для переменных команд
В командной строке можно использовать следующие типы данных для переменных.
How to find the number of occurrences of a string in file using windows command line?
I have a huge files with e-mail addresses and I would like to count how many of them are in this file. How can I do that using Windows’ command line ?
I have tried this but it just prints the matching lines. (btw : all e-mails are contained in one line)
findstr /c:»@» mail.txt
9 Answers 9
Using what you have, you could pipe the results through a find . I’ve seen something like this used from time to time.
So you are counting the lines resulting from your findstr command that do not have the garbage string in it. Kind of a hack, but it could work for you. Alternatively, just use the find /c on the string you do care about being there. Lastly, you mentioned one address per line, so in this case the above works, but multiple addresses per line and this breaks.
Why not simply using this (this determines the number of lines containing (at least) an @ char.):
To avoid the file name in the output, change it to this:
To capture the resulting number and store it in a variable, use this (change %N to %%N in a batch file):
Very simple solution:
Remember a dot at end of line!
Here is little bit more understandable way:
First grep selects only «@» strings and put each on new line.
Second grep counts lines (or lines with @).
The grep utility can be installed from GnuWin project or from WinGrep sites. It is very small and safe text filter. The grep is one of most usefull Unix/Linux commands and I use it in both Linux and Windows daily. The Windows findstr is good, but does not have such features as grep.
Installation of the grep in Windows will be one of the best decision if you like CLI or batch scripts.
May be it’s a little bit late, but the following script worked for me (the source file contained quote characters, this is why I used ‘usebackq’ parameter). The caret sign(^) acts as escape character in windows batch scripting language.
I found this on the net. See if it works:
I would install the unix tools on your system (handy in any case :-), then it’s really simple — look e.g. here:
You can get the Windows unix tools here:
OK — way late to the table, but. it seems many respondents missed the original spec that all email addresses occur on 1 line. This means unless you introduce a CRLF with each occurrence of the @ symbol, your suggestions to use variants of FINDSTR /c will not help.
Among the Unix tools for DOS is the very powerful SED.exe. Google it. It rocks RegEx. Here’s a suggestion:
Explanation: (assuming the file with the data is named «Datafile.txt») 1) The 1st FIND includes 3 lines of header info, which throws of a line-count approach, so pipe the results to a 2nd (identical) find to strip off unwanted header info.
2) Pipe the above results to SED, which will search for each «@» character and replace it with itself+ «\n» (which is a «new line» aka a CRLF) which gets each «@» on its own line in the output stream.
3) When you pipe the above output from SED into the FIND /n command, you’ll be adding line numbers to the beginning of each line. Now, all you have to do is isolate the numeric portion of each line and preface it with «SET /a» to convert each line into a batch statement that (increasingly with each line) sets the variable equal to that line’s number.
4) isolate each line’s numeric part and preface the isolated number per the above via:
| SED «s/\[\(.*\)\].*/Set \/a NumFound=\1/»
In the above snippet, you’re piping the previous commands’s output to SED, which uses this syntax «s/WhatToLookFor/WhatToReplaceItWith/», to do these steps:
a) look for a «[» (which must be «escaped» by prefacing it with «\»)
b) begin saving (or «tokenizing») what follows, up to the closing «]»
c) the stuff between the \( and the \) is «tokenized», which means it can be referred-to later, in the «WhatToReplaceItWith» section. The first stuff that’s tokenized is referred to via «\1» then second as «\2», etc.
So. we’re ignoring the [ and the ] and we’re saving the number that lies between the brackets and IGNORING all the wild-carded remainder of each line. thus we’re replacing the line with the literal string: Set /a NumFound= + the saved, or «tokenized» number, i.e. . the first line will read: Set /a NumFound=1 . & the next line reads: Set /a NumFound=2 etc. etc.
Thus, if you have 1,283 email addresses, your results will have 1,283 lines.
The last one executed = the one that matters.
If you use the «>» character to redirect all of the above output to a batch file, i.e.: > CountChars.bat
. then just call that batch file & you’ll have a DOS environment variable named «NumFound» with your answer.
Base64 Encode “string” — command-line Windows?
I have found numerous ways to base64 encode whole files using the command-line on Windows, but I can’t seem to find a simple way to batch encode just a «string» using a command-line utility.
How does one do this, for use in a batch file for example?
7 Answers 7
Here’s a PowerShell one-liner you can run from a cmd console that’ll Base64 encode a string.
It’s probably not as fast as npocmaka’s solution, but you could set a console macro with it.
Be advised that doskey doesn’t work in batch scripts — only the console. If you want do use this in a batch script, make a function.
Or if you’d prefer a batch + JScript hybrid:
Edit: batch + VBScript hybrid for @Hackoo:
According to the comments on the question, you can use certutil. e.g.,
The -f means «force overwrite». Otherwise you will get an error if the output file (encoded.txt above) already exists.
However, this will format the output into the encoded.txt file as if it were a certificate PEM file, complete with BEGIN and END lines, and split lines at the character max. So you would need to do further processing in a batch scenario, and a bit of extra work if the strings are long at all.
This script can decode/encode base64 strings on every machine from XP and above without requiring installed .net or internet explorer 10/11.It even can handle special javascript escaped symbols:
This one accepts a single argument — the string you want to encode to base 64 and prints the result (but requires at least internet explorer 10 installed):
If you have OpenSSL for Windows installed you can use this to encode the string «Hello»:
The | set /p= is to suppress the newline that echo usually outputs.
This will produce the same result as the following in bash:
This can (technically) be done entirely within Batch, By Creating an encryption\decryption VBS script from within batch that can be called with the name of the Variable whose Data you wish to encrypt\decrypt.
Note: The below scipt is an Independant Subprogram.
Hybrid Batch Vbs Encrypter / Decrypter for passwords or other variables. Performs the action on data stored in the defined file — does not create the file.
Note: file extension in vbs to match the filetype you save password/text to.
To use this program Call it with the name of the Variable you wish to set and the offset to perform.
However your Main program takes user input:
Store the Input to a File
Call it with a positive offset (IE: +26) to encrypt, and an equivalent Negative offset to Decrypt. (IE: -26)