- How to Split Large Text File into Smaller Files in Linux
- Split
- Split Examples
- Split a file into multiple pieces by default usage
- Split the file, based upon the number of lines
- Split a large file into 500MB files
- Split a large file into 200MB files with the given prefix
- Split the file and name it with numbers
- Csplit
- Csplit Examples
- Split files based on the number of lines
- Split files using regular expressions
- Split files with the given prefix
- Split a file by suppressing a line that matches the input pattern
- Customize the number of digits in the output files names
- Forcing csplit to save the output file in case of error
- Wrapping up
- 11 Useful Split Command Examples for Linux Systems
- Example: 1) Split File into Pieces
- Example: 2) Split Command with verbose option
- Example: 3) Split files with customize line numbers (-l)
- Example: 4) Split files with file size using option -b
- Example: 5) Create Split files with numeric suffix instead of alphabetic (-d)
- Example: 6) Split file with Customize Suffix
- Example: 7) Generate n chunks output files with split command (-n)
- Example: 8) Prevent Zero Size Split output files with option (-e)
- Example:9) Create Split output files of customize suffix length (-a option)
- Example: 10) Split ISO file and merge it into a single file.
- Example: 11) Verify the Integrity of Merge file using md5sum utility
- 9 полезных примеров команды Split в Linux
- Примеры команды Split в Linux
- 1. Разделите файлы на несколько файлов
- 2. Разделите файлы на несколько файлов с определенными номерами строк
- 3. Разделение файлов на n файлов
- 4. Разделение файлов с пользовательским префиксом имени
- 5. Разделите и укажите длину суффикса
- 6. Разделить с помощью числового суффикса заказа
- 7. Добавьте шестнадцатеричные суффиксы для разделения файлов
- 8. Разделите файлы на несколько файлов определенного размера
- 9. Разбивка файлов на несколько с определенным размером файла
- Бонусный совет: воссоединение разделенных файлов
How to Split Large Text File into Smaller Files in Linux
Linux has several utilities for breaking down large files into small files. Split and csplit are two of the popular commands which are used for this purpose. These utilities will help to break down big log files and even archive files to make it into a smaller size. This will make convenient to split large files into smaller sizes so that it fits on smaller media storage devices like USB to meet our purpose. By this technique, we can even speed up network file transfers, because parallel transfers of small files are usually faster.
In this tutorial, I’ll explain more on how to use these split and csplit utilities to break-down large files in Linux.
Split
To split large files into smaller files, we can use this command utility in Linux.
You can replace filename with the name of the large file you wish to split. And «prefix» with the name you wish to give the small output files. You can exclude [options], or replace it with either of the following:
The split command will give each output file it creates the name prefix with an extension tacked to the end that indicates its order. By default, the split command adds aa to the first output file, proceeding through the alphabet to zz for subsequent files. By default, most systems use x as the prefix.
Split Examples
Split command splits the file into n lines per file and names the files as PREFIXaa, PREFIXab, PREFIXac, and so on. By default the PREFIX is x , and the number of lines is 1000 lines per file.
Split a file into multiple pieces by default usage
I’ve my log file namely system log with 1099 lines, let’s see the status of my log file after splitting it using this command.
The command splits the log file into two files xaa and xab, with the first one having 1000 lines and dumps the leftover in the second file.
Split the file, based upon the number of lines
We can split the file into multiple pieces based on the number of lines using -l option. Here, I’m splitting my system log file with 1099 lines into smaller files with 200 lines each. Let’s see the commands for the same:
You can see that the command has split my log file into five smaller files with 200 lines each and the last one with the leftover.
Split a large file into 500MB files
You can use the option -b to specify the required size limit to split the files. Please see this command which I used for splitting my 1GB Apache log file into two 500MB files each.
Split a large file into 200MB files with the given prefix
You can use the option -b to specify the 200M file size and the required prefix as the second argument. Please see the command which I used to split my 1GB Apache log to 200MB files with a prefix named split.log below:
In this example, you can see that my log files are broken down into 200MB files with my required prefix.
Split the file and name it with numbers
You can use the option -d to name the files with number suffixes as 00, 01, 02 .. and so on, instead of aa, ab, ac. Please see the command which I used to split my 1GB Apache log to 200MB files with a prefix named log and add numbers to the suffix using the option -d instead of alphabets below:
You can see the manual page of split command using the command man split to see more information.
Csplit
Csplit is another command utility which divides single files into multiple files determined by context lines.
The files created by csplit normally have names of the form
xxnumber
where number is a two digit decimal number which begins at zero and it increments by one for each new file that csplit creates.
csplit also displays the size, in bytes, of each file that it creates as output.
Csplit Examples
By default, the files that csplit produces in output have ‘xx’ as the prefix and the numbers produced in the output are the byte count for the files the command produced.
Split files based on the number of lines
I have a file which contains 8 lines with the domain names, and my requirement is to split that file at the fourth line, then this can be done by passing ‘4’ as a command line argument after the command and file name.
By passing 4 as a command-line argument, this command splits our domainslist file at the 4th line. The numbers produced in the output are the byte count for the files the command produced. Apparently, two files were produced in the output, namely xx00 and xx01.
Split files using regular expressions
We can use regular expressions with the csplit command. For example, in the previous case, if you want the command to repeat the pattern one more time, then you can do this using the following command:
In this case, we can get three output files.
You can use the asterisk wildcard <*>to tell csplit to repeat your split as many times as possible.
Split files with the given prefix
By default, csplit spilts files and produces the output files to have xx as the prefix. However, if you want, you can change that default prefix using the option -f in the command line with a required prefix.
For example, the following command will produce files having ‘domain’ as prefix.
Split a file by suppressing a line that matches the input pattern
This csplit command provides an option to suppress lines that match the input pattern. The option in question is —suppress-matched .
For example, the following command splits our file at line 4 (xx00 will contain upto line 3, while xx11 will contain rest of the lines excluding line 4).
Customize the number of digits in the output files names
By default, the number of digits that follow the prefix in the output filename is 2. We can use this option -n to customize the number of digits following the prefix in the output file names. For example, if you want to have names like xx001, you can use the command line option which requires the input number signifying the number of digits like -n 3 as below:
Forcing csplit to save the output file in case of error
By default, csplit removes the output files created in case of any error situation. However, if you want to forcefully save this output file by using the -k option in the command. Please check this example to see the difference in the execution of this command with and without -k option.
By default, csplit removes the output files created in case of any error situation. However, we can forcefully save this output file by using the ‘-k’ option in the command. Please check this example to see the difference in the execution of this command with and without -k option. On this first example, the command is meant to split our file ‘domainslist’ on line 3 and repeat the command twice like that which means it should split the second file too at line 3 and should repeat it once again. But since our source file has only eight lines, after the first split it repeats once but unable to iterate twice due to the insufficient range. Hence, no output files are produced due to this error.
But when we executed the same command with this option -k, the output files were not deleted. Please see the result below:
You can check the man page for this tool using man csplit to get more information about this.
Wrapping up
These command-line utilities may not be required for a Linux user on daily basis, but this is one of the important utility which will be helpful for you in your server administration. I hope this article explained all the basic options and uses for these tools. Please post your valuable comments and suggestions on this.
Источник
11 Useful Split Command Examples for Linux Systems
As the name suggests ‘split‘ command is used to split or break a file into the pieces in Linux and UNIX systems. Whenever we split a large file with split command then split output file’s default size is 1000 lines and its default prefix would be ‘x’.
In this article we will discuss 11 useful split command examples for Linux Users. Apart from this we will also discuss how split files can be merge or reassembled into a single file. Syntax for split command:
Some of the important options of split command is shown below:
Example: 1) Split File into Pieces
Let’s assume we have file name with tuxlap.txt, Use below split command to break into the pieces
As we can see the above output ‘tuxlab.txt‘ is split into two pieces with the name ‘xaa’ and ‘xab’.
Example: 2) Split Command with verbose option
We can run split command in verbose mode with option ‘–verbose‘, example is shown below:
Example: 3) Split files with customize line numbers (-l)
Let’s suppose we want to split a file with customize line numbers, let say I want max 200 lines per file.
To achieve this, use ‘-l’ option in split command.
Verify the lines of each file using below command
Example: 4) Split files with file size using option -b
Using Split command we can split a file with file size. Use the following syntax to split files with size in bytes, KB , MB and GB
# split -b nK
# split -b nM
# split -b nG
Split file based on bytes:
Split file based on KB:
Split file based on MB:
Split file based on GB:
Example: 5) Create Split files with numeric suffix instead of alphabetic (-d)
In the above examples we have seen that split command output files are created with alphabetic suffix like xaa, xab….. xan , Use ‘-d’ option with split command to create split output files with numeric suffix like x00, x01, … x0n
Example: 6) Split file with Customize Suffix
With split command we can create split output files with customize suffix. Let’s assume we want to create split output files with customize suffix
Syntax:
Example: 7) Generate n chunks output files with split command (-n)
Let’s suppose we want to split an iso file into 4 chunk output files. Use ‘-n’ option with split command limit the number of split output files.
Verify the Split out files using ll command.
Example: 8) Prevent Zero Size Split output files with option (-e)
There can be some scenarios where we split a small file into a large number of chunk files and zero size split output files can be created in such cases, so to avoid zero size split output file, use the option ‘-e’
Example:9) Create Split output files of customize suffix length (-a option)
Let’s suppose we want to split an iso file and where size of each split output file is 500MB and suffix length is to be 3. Use the following split command:
Example: 10) Split ISO file and merge it into a single file.
Let’s suppose we have a Windows Server ISO file of size 4.2 GB and we are unable to scp this file to remote server because of its size.
To resolve such type of issues we can split the ISO into n number of pieces and will copy these pieces to remote sever and on the remote server we can merge these pieces into a single file using cat command,
View the split output files using ll command,
Now scp these files to remote server and merge these files into a single using cat command
Example: 11) Verify the Integrity of Merge file using md5sum utility
As per Example 10, once the split output files are merged into a single file, then we can check the integrity of actual & merge file with md5sum utility. Example is shown below:
As per the above output, it is confirm that integrity is maintained and we can also say split file are successfully restored to a single file.
That’s all from this article, If you like these examples then please do share your valuable feedback and comments in the comments section below.
Read Also : 16 Echo Command Examples in Linux
Источник
9 полезных примеров команды Split в Linux
Главное меню » Операционная система Linux » 9 полезных примеров команды Split в Linux
Обратите внимание, что мы не будем отображать вывод напрямую в этих примерах из-за больших размеров файлов. Мы будем использовать команды ll и wc для выделения изменений файла.
Мы советуем вам быстро взглянуть на команду wc, чтобы понять вывод примеров команды split.
Примеры команды Split в Linux
Синтаксис команды Split:
Давайте посмотрим, как использовать его для разделения файлов в Linux.
1. Разделите файлы на несколько файлов
По умолчанию команда split создает новые файлы для каждых 1000 строк. Если префикс не указан, он будет использовать ‘x’. Следующие буквы перечисляют файлы, поэтому сначала идет xaa, затем xab и так далее.
Давайте разделим пример файла журнала:
Если вы используете команду ls, вы можете увидеть несколько новых файлов в вашем каталоге.
Вы можете использовать wc для быстрой проверки количества строк после разделения.
Помните, что ранее мы видели, что наш исходный файл содержал 17 170 строк. Таким образом, мы можем видеть, что наша программа создала как и ожидалось, 18 новых файлов. 17 из них заполнены 1000 строками в каждой, а последняя имеет оставшиеся 170 строк.
Другой способ продемонстрировать, что происходит, – запустить команду с параметром verbose. Если вы не знакомы с verbose, вы пропускаете! Он предоставляет более подробные отзывы о том, что делает ваша система, и он доступен для использования со многими командами.
Вы можете увидеть, что происходит с вашей командой на дисплее:
2. Разделите файлы на несколько файлов с определенными номерами строк
Мы понимаем, что вам может не понравиться, что файлы разбиты на файлы по 1000 строк. Вы можете изменить это поведение с помощью опции -l.
Теперь вы можете указать, сколько строк вы хотите в каждом из новых файлов.
Как вы можете догадаться, теперь разделенные файлы имеют по 500 строк каждая, кроме последней.
Теперь у вас есть намного больше файлов, но с половиной строк в каждом.
3. Разделение файлов на n файлов
Опция -n делает разделение на указанное число частей или кусков. Вы можете назначить, сколько файлов вы хотите, добавив целочисленное значение после -n.
Теперь вы можете видеть, что есть 15 новых файлов.
4. Разделение файлов с пользовательским префиксом имени
Что делать, если вы хотите использовать split, но оставить оригинальное имя моего файла или вообще создать новое имя вместо ‘x’?
Возможно, вы помните, что видели префикс как часть синтаксиса, описанного в начале статьи. Вы можете написать свое собственное имя файла после исходного файла.
Вот разделенные файлы с именами, начинающимися с данного префикса.
5. Разделите и укажите длину суффикса
Разделение имеет длину суффикса по умолчанию 2 [aa, ab и т. д.]. Это изменится автоматически при увеличении количества файлов, но если вы хотите изменить его вручную, это тоже возможно. Допустим, вы хотите, чтобы наши файлы были названы как-то вроде AndreyExSeparatedLogFiles.log_aaaab.
Как ты можешь это сделать? Опция -a позволяет нам указать длину суффикса.
И вот разделенные файлы:
6. Разделить с помощью числового суффикса заказа
До этого момента вы видели, что ваши файлы разделены с использованием различных буквенных комбинаций. Лично нам гораздо проще различать файлы по номерам.
Давайте сохраним длину суффикса из предыдущего примера, но изменим алфавитную организацию на числовую с помощью опции -d.
Так что теперь у вас будут разделенные файлы с числовыми значениями.
7. Добавьте шестнадцатеричные суффиксы для разделения файлов
Другой вариант создания суффикса – использовать встроенный шестнадцатеричный суффикс, который чередует упорядоченные буквы и цифры.
В этом примере мы объединяем несколько вещей, которые мы вам уже показали. Мы разделим файл, используя свой собственный префикс и выбрали подчеркивание для удобства чтения.
Мы использовали опцию -x для создания шестнадцатеричного суффикса. Затем разделили наш файл на 50 кусков и дали суффиксу длину 6.
И вот результат вышеупомянутой команды:
8. Разделите файлы на несколько файлов определенного размера
Также возможно использовать размер файла, чтобы разбить файлы в разбивке. Возможно, вам нужно отправить большой файл по сети с ограниченным размером как можно более эффективно. Вы можете указать точный размер для ваших требований.
Синтаксис может стать немного сложнее, так как мы продолжаем добавлять опции. Итак, мы объясним, как работает команда, прежде чем показывать пример.
Если вы хотите создать файлы определенного размера, используйте опцию -b. Затем вы можете написать n K [B], n M [B], n G [B], где n – это значение размера вашего файла, а K [1024] – это -kibi, M – -mebi, G – -gibi и далее. КБ [1000] – килограмм, МБ – мега и т. д.
Может показаться, что многое происходит, но это не так сложно, когда разбиваешь это. Вы указали исходный файл, наш префикс имени файла назначения, числовой суффикс и разделение по размеру файла 128 КБ.
Вот разделенные файлы:
Вы можете проверить результат с помощью команды wc.
9. Разбивка файлов на несколько с определенным размером файла
Если вы хотите разбить файлы примерно на один и тот же размер, но сохранить структуру строк , это может быть лучшим выбором для вас. С помощью -C, вы можете указать максимальный размер. Затем программа автоматически разбивает файлы на основе полных строк.
В выводе вы можете видеть, что первый разделенный файл имеет размер около 1 МБ, тогда как остальная часть файла находится во втором файле.
Бонусный совет: воссоединение разделенных файлов
Это не команда split, но она может быть полезна для новых пользователей.
Вы можете использовать другую команду, чтобы присоединиться к этим файлам и создать копию нашего полного документа. Команда cat – это сокращение от конкатенации, это просто причудливое слово, означающее «объединить элементы вместе». Поскольку все файлы начинаются с буквы «х», звездочка будет применять команду ко всем файлам, которые начинаются с этой буквы.
Как видите, наш воссозданный файл имеет тот же размер, что и наш оригинал.
Наше форматирование (включая количество строк) сохраняется в созданном файле.
Если вы новичок в Linux, мы надеемся, что это руководство помогло вам понять команду split. Если вы более опытны, расскажите нам ваш любимый способ использовать разделение в комментариях ниже!
Если вы нашли ошибку, пожалуйста, выделите фрагмент текста и нажмите Ctrl+Enter.
Источник