Understanding the cut Command

Basic Usage of cut

The cut command in Linux is used to extract sections from each line of files or input streams based on byte, character, or field positions.

cut [OPTION]... [FILE]...

With cut, you can slice sections of data such as columns or fields from text files or outputs.

Options Available with cut

-b (Select Bytes)

Select specific bytes from a file:

cut -b 1-4 file.txt

This command extracts bytes 1 through 4 from each line of file.txt.

-c (Select Characters)

Extract specific characters:

cut -c 2-5 file.txt

This command extracts characters 2 through 5 from each line of file.txt.

-f (Select Fields)

Extract fields based on a delimiter (default is tab):

cut -f 2,4 file.txt

This command extracts the 2nd and 4th fields from file.txt. Fields are separated by tabs by default.

-d (Define Delimiter)

Specify the field delimiter (use with -f):

cut -d ',' -f 1,3 file.txt

This command extracts the 1st and 3rd fields using a comma (',') as the delimiter.

--complement (Complement)

Complement the selected range, i.e., select everything except the specified fields, bytes, or characters:

cut -f 1 --complement file.txt

This command will select all fields except the 1st one.

--output-delimiter (Set Output Delimiter)

Define a delimiter for the output:

cut -d ',' -f 1,3 --output-delimiter='|' file.txt

This extracts the 1st and 3rd fields and separates them with a pipe character ('|') in the output.

--help

Display help information about the cut command:

cut --help

Examples of cut Command

Extracting Specific Characters

cut -c 1-3 file.txt

This command extracts the first three characters from each line in file.txt.

Extracting Fields Using a Custom Delimiter

cut -d ':' -f 1,3 /etc/passwd

This command extracts the 1st and 3rd fields from the /etc/passwd file, where fields are delimited by a colon (':').

Using Output Delimiter

cut -d ',' -f 2,4 --output-delimiter=' ' file.csv

In this case, the fields 2 and 4 from file.csv will be separated by a space (' ') in the output.

Summary of Options

Option Description
-b Select specific bytes from each line.
-c Select specific characters from each line.
-f Select specific fields (columns) from each line.
-d Specify the delimiter to be used for fields.
--complement Select everything except the specified range.
--output-delimiter Set the delimiter for the output fields.
--help Display help for the cut command.

Manual Pages

For more detailed information, you can refer to the manual page for the cut command:

man cut