Open In App

csplit command in Linux with examples

Last Updated : 25 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The ‘csplit’ command is used to split any file into many parts as required by the user. The parts are determined by context lines. Output pieces of FILE separated by PATTERN(s) to files ‘xx00’, ‘xx01’, …, and output byte counts of each piece to standard output.

Here, we will explain how to use ‘csplit’ effectively, with examples and detailed explanations of the most commonly used options.

Syntax

csplit [OPTION]… FILE PATTERN…

Here, FILE refers to the file to be split, and PATTERN specifies where to divide the file. The ‘csplit’ command supports a variety of options that control how the output files are named, how many digits are used in their names, and whether empty files should be removed.

Basic Example csplit Command

Example: Splitting a File by Line Numbers

Consider a text file named ‘list.txt’ with contents as follows:

Now split this file into two parts (second part starting from 3rd line) using csplit command as follows:

csplit list.txt 2

Common Options for the csplit Command

1. -f, –Prefix:

It use PREFIX in place of ‘xx’. Example: Here instead of ‘xx’ prefix ‘abc was used.

2. -k, –Keep files:

This option will not remove the output files on errors.

Example: This command removes all output files in case it encounters an error. This can be changed by using ‘-k‘ option.

3. -n, –Digits:

Use given number of digits instead of 2. Example: Here we fixed number of digits after the file name. So instead of ‘xx01’ we get ‘xx0’.

4. -z, –elide-empty-files:

Remove empty output files.

Example: This removed the empty output files.

Other Important Options For csplit command

Option Description
-s, –quiet Does not display the counts of output file sizes.
-b, –suffix-format Use sprintf format instead of %02d for file suffixes.
–help Displays the help message and exits.
–version Displays the version information of the csplit command and exits.

Conclusion

The csplit command is a powerful tool for splitting files into smaller parts based on patterns or context lines. With options like custom prefixes, file digit control, and the ability to remove empty files, csplit offers flexibility and control in file manipulation. By mastering csplit, you can more efficiently work with large files in Linux, breaking them down into manageable sections tailored to your needs.


Next Article

Similar Reads