Сведения о разбиении About Split
КРАТКОЕ ОПИСАНИЕ SHORT DESCRIPTION
Объясняет, как использовать оператор Split для разделения одной или нескольких строк на подстроки. Explains how to use the Split operator to split one or more strings into substrings.
ПОДРОБНОЕ ОПИСАНИЕ LONG DESCRIPTION
Оператор Split разделяет одну или несколько строк на подстроки. The Split operator splits one or more strings into substrings. Вы можете изменить следующие элементы операции разбиения: You can change the following elements of the Split operation:
- Разделитель. Delimiter. По умолчанию используется пробел, но можно указать символы, строки, шаблоны или блоки скриптов, указывающие разделитель. The default is whitespace, but you can specify characters, strings, patterns, or script blocks that specify the delimiter. Оператор Split в PowerShell использует регулярное выражение в разделителе, а не простой символ. The Split operator in PowerShell uses a regular expression in the delimiter, rather than a simple character.
- Максимальное число подстрок. Maximum number of substrings. По умолчанию возвращаются все подстроки. The default is to return all substrings. Если указать число, меньшее числа подстрок, оставшиеся подстроки объединяются в последнюю подстроку. If you specify a number less than the number of substrings, the remaining substrings are concatenated in the last substring.
- Параметры, определяющие условия, при которых будет сопоставляться разделитель, например SimpleMatch и Multiline. Options that specify the conditions under which the delimiter is matched, such as SimpleMatch and Multiline.
SYNTAX SYNTAX
На следующей схеме показан синтаксис оператора-split. The following diagram shows the syntax for the -split operator.
Имена параметров не отображаются в команде. The parameter names do not appear in the command. Включайте только значения параметров. Include only the parameter values. Значения должны присутствовать в порядке, указанном в схеме синтаксиса. The values must appear in the order specified in the syntax diagram.
Можно заменить -iSplit или -cSplit для -split в любой инструкции двоичного разделения (оператор разбиения, включающий разделитель или блок сценария). You can substitute -iSplit or -cSplit for -split in any binary Split statement (a Split statement that includes a delimiter or script block). В -iSplit -split операторах и регистр не учитывается. The -iSplit and -split operators are case-insensitive. В -cSplit операторе учитывается регистр, что означает, что при применении правил разделителей учитывается регистр. The -cSplit operator is case-sensitive, meaning that case is considered when the delimiter rules are applied.
PARAMETERS PARAMETERS
или or
Указывает одну или несколько строк для разбиения. Specifies one or more strings to be split. При отправке нескольких строк все строки разбиваются с помощью одних и тех же правил разделителей. If you submit multiple strings, all the strings are split using the same delimiter rules.
Символы, которые обозначают конец подстроки. The characters that identify the end of a substring. По умолчанию разделителем являются пробелы, включая пробелы и непечатаемые символы, например символ новой строки ( ` n) и знак табуляции ( ` t). The default delimiter is whitespace, including spaces and non-printable characters, such as newline (`n) and tab (`t). При разбиении строк разделитель опускается из всех подстрок. When the strings are split, the delimiter is omitted from all the substrings. Пример. Example:
По умолчанию разделитель в результатах опускается. By default, the delimiter is omitted from the results. Чтобы сохранить все или часть разделителя, заключите в круглые скобки часть, которую необходимо сохранить. To preserve all or part of the delimiter, enclose in parentheses the part that you want to preserve. Если параметр добавлен, это имеет приоритет, если команда разделяет коллекцию. If the parameter is added, this takes precedence when your command splits up the collection. Если включить разделитель как часть выходных данных, команда возвращает разделитель в составе выходных данных. Однако разделение строки для возврата разделителя в качестве части выходных данных не учитывается в качестве разбиения. If you opt to include a delimiter as part of the output, the command returns the delimiter as part of the output; however, splitting the string to return the delimiter as part of output does not count as a split.
Указывает максимальное количество подстрок, возвращаемых операцией разбиения. Specifies the maximum number of substrings returned by the split operation. По умолчанию используются все подстроки, разделенные разделителем. The default is all substrings split by the delimiter. Если подстроки больше, они объединяются с конечной подстрокой. If there are more substrings, they are concatenated to the final substring. Если число подстрок меньше, возвращаются все подстроки. If there are fewer substrings, all substrings are returned. Значение 0 возвращает все подстроки. A value of 0 returns all the substrings.
Если в оператор отправляется более одной строки (массив строк) -split , то Max-substrings ограничение применяется к каждой строке отдельно. If you submit more than one string (an array of strings) to the -split operator, the Max-substrings limit is applied to each string separately.
не указывает максимальное число возвращаемых объектов. does not specify the maximum number of objects that are returned. В следующем примере значение равно 3. In the following example, is set to 3. В результате получается три значения подстроки, а в результирующем выводе всего пять строк. This results in three substring values, but a total of five strings in the resulting output. Разделитель включается после разбиения до тех пор, пока не будет достигнуто максимальное число, равное трем подстрокам. The delimiter is included after the splits until the maximum of three substrings is reached. Дополнительные разделители в конечной подстроке становятся частью подстроки. Additional delimiters in the final substring become part of the substring.
Отрицательные значения возвращают количество подстрок, запрошенных начиная с конца входной строки. Negative values return the amount of substrings requested starting from the end of the input string.
В PowerShell 7 добавлена поддержка отрицательных значений. Support for negative values was added in PowerShell 7.
Выражение, задающее правила для применения разделителя. An expression that specifies rules for applying the delimiter. Выражение должно иметь значение $true или $false. The expression must evaluate to $true or $false. Заключите блок скрипта в фигурные скобки. Enclose the script block in braces.
Заключите имя параметра в кавычки. Enclose the option name in quotation marks. Параметры допустимы только в том случае, если параметр используется в инструкции. Options are valid only when the parameter is used in the statement.
Для параметра options используется следующий синтаксис: The syntax for the Options parameter is:
Параметры SimpleMatch: The SimpleMatch options are:
- SimpleMatch: Используйте простое сравнение строк при вычислении разделителя. SimpleMatch: Use simple string comparison when evaluating the delimiter. Не может использоваться с Режексматч. Cannot be used with RegexMatch.
- IgnoreCase: принудительное сопоставление без учета регистра, даже если указан оператор-ксплит. IgnoreCase: Forces case-insensitive matching, even if the -cSplit operator is specified.
Параметры Режексматч: The RegexMatch options are:
- Режексматч: используйте сопоставление регулярных выражений для вычисления разделителя. RegexMatch: Use regular expression matching to evaluate the delimiter. Это поведение установлено по умолчанию. This is the default behavior. Не может использоваться с SimpleMatch. Cannot be used with SimpleMatch.
- IgnoreCase: принудительное сопоставление без учета регистра, даже если указан оператор-ксплит. IgnoreCase: Forces case-insensitive matching, even if the -cSplit operator is specified.
- CultureInvariant: игнорирует культурные различия в языке, если оценка разделитель. CultureInvariant: Ignores cultural differences in language when evaluting the delimiter. Допустимо только с Режексматч. Valid only with RegexMatch.
- IgnorePatternWhitespace: игнорирует неэкранированные пробелы и комментарии, помеченные знаком решетки (#). IgnorePatternWhitespace: Ignores unescaped whitespace and comments marked with the number sign (#). Допустимо только с Режексматч. Valid only with RegexMatch.
- Многострочный: многострочный режим заставляет ^ и $ сопоставлять начальную конец каждой строки, а не начало и конец входной строки. Multiline: Multiline mode forces ^ and $ to match the beginning end of every line instead of the beginning and end of the input string.
- SingleLine: режим SingleLine обрабатывает входную строку как SingleLine. Singleline: Singleline mode treats the input string as a SingleLine. Он заставляет . символ соответствовать каждому символу (включая символы новой строки) вместо того, чтобы сопоставлять каждый символ, кроме символа новой строки \n . It forces the . character to match every character (including newlines), instead of matching every character EXCEPT the newline \n .
- ExplicitCapture: игнорирует неименованные группы соответствия, чтобы в списке результатов возвращались только явные группы записи. ExplicitCapture: Ignores non-named match groups so that only explicit capture groups are returned in the result list. Допустимо только с Режексматч. Valid only with RegexMatch.
ОПЕРАТОРЫ УНАРного и БИНАРного разделения UNARY and BINARY SPLIT OPERATORS
Оператор унарного разбиения ( -split ) имеет более высокий приоритет, чем запятая. The unary split operator ( -split ) has higher precedence than a comma. В результате, если отправить разделенный запятыми список строк в оператор унарного разбиения, то разбиение выполняется только на первую строку (перед первой запятой). As a result, if you submit a comma-separated list of strings to the unary split operator, only the first string (before the first comma) is split.
Чтобы разделить более одной строки, используйте один из следующих шаблонов: Use one of the following patterns to split more than one string:
- Использование оператора двоичного разделения ( -Split ) Use the binary split operator ( -split )
- Заключите все строки в круглые скобки Enclose all the strings in parentheses
- Сохранить строки в переменной, а затем отправить переменную оператору Split Store the strings in a variable then submit the variable to the split operator
Рассмотрим следующий пример. Consider the following example:
Примеры EXAMPLES
Следующая инструкция разделяет строку на пробел. The following statement splits the string at whitespace.
Следующая инструкция разделяет строку на любую запятую. The following statement splits the string at any comma.
Следующая инструкция разделяет строку на шаблоне «ER». The following statement splits the string at the pattern «er».
Следующая инструкция выполняет разбиение с учетом регистра по букве «N». The following statement performs a case-sensitive split at the letter «N».
Следующая инструкция разделяет строку на «e» и «t». The following statement splits the string at «e» and «t».
Следующая инструкция разделяет строку на «e» и «r», но ограничивает результирующие подстроки до шести подстрок. The following statement splits the string at «e» and «r», but limits the resulting substrings to six substrings.
Следующая инструкция разделяет строку на три подстроки. The following statement splits a string into three substrings.
Следующая инструкция разделяет строку на три подстроки, начиная с конца строки. The following statement splits a string into three substrings starting from the end of the string.
Следующая инструкция разделяет две строки на три подстроки. The following statement splits two strings into three substrings. (Ограничение применяется к каждой строке независимо друг от друга.) (The limit is applied to each string independently.)
Следующая инструкция разделяет каждую строку в строке Here в первой цифре. The following statement splits each line in the here-string at the first digit. Он использует многострочный параметр для распознавания начала каждой строки и строки. It uses the Multiline option to recognize the beginning of each line and string.
0 представляет значение «вернуть все» для параметра max-substring. The 0 represents the «return all» value of the Max-substrings parameter. Параметры, например Multiline, можно использовать, только если указано значение Max-substring. You can use options, such as Multiline, only when the Max-substrings value is specified.
Следующая инструкция использует символ обратной косой черты для экранирования разделителя с точкой (.). The following statement uses the backslash character to escape the dot (.) delimiter.
При использовании значения по умолчанию Режексматч точка, заключенная в кавычки («.»), интерпретируется так, чтобы соответствовать любому символу, кроме символа новой строки. With the default, RegexMatch, the dot enclosed in quotation marks («.») is interpreted to match any character except for a newline character. В результате инструкция Split возвращает пустую строку для каждого символа, кроме новой строки. As a result, the Split statement returns a blank line for every character except newline.
В следующей инструкции используется параметр SimpleMatch для направления оператора-split на интерпретацию разделителя с точкой (.) буквально. The following statement uses the SimpleMatch option to direct the -split operator to interpret the dot (.) delimiter literally.
0 представляет значение «вернуть все» для параметра max-substring. The 0 represents the «return all» value of the Max-substrings parameter. Параметры, такие как SimpleMatch, можно использовать, только если указано значение Max-substring. You can use options, such as SimpleMatch, only when the Max-substrings value is specified.
Следующая инструкция разделяет строку на один из двух разделителей в зависимости от значения переменной. The following statement splits the string at one of two delimiters, depending on the value of a variable.
How to split large text file in windows?
I have a log file with size of 2.5 GB. Is there any way to split this file into smaller files using windows command prompt?
6 Answers 6
If you have installed Git for Windows, you should have Git Bash installed, since that comes with Git.
Use the split command in Git Bash to split a file:
into files of size 500MB each: split myLargeFile.txt -b 500m
into files with 10000 lines each: split myLargeFile.txt -l 10000
Tips:
If you don’t have Git/Git Bash, download at https://git-scm.com/download
If you lost the shortcut to Git Bash, you can run it using C:\Program Files\Git\git-bash.exe
That’s it!
I always like examples though.
Example:
You can see in this image that the files generated by split are named xaa , xab , xac , etc.
These names are made up of a prefix and a suffix, which you can specify. Since I didn’t specify what I want the prefix or suffix to look like, the prefix defaulted to x , and the suffix defaulted to a two-character alphabetical enumeration.
Another Example:
This example demonstrates
- using a filename prefix of MySlice (instead of the default x ),
- the -d flag for using numerical suffixes (instead of aa , ab , ac , etc. ),
- and the option -a 5 to tell it I want the suffixes to be 5 digits long: