Linux Cut Command: Extract Fields from a File

The cut command is a standard command-line utility in the Linux operating system designed for parsing and filtering text streams. This article explains how the cut command extracts specific fields from structured data files, covering its primary syntax, essential flags such as -d and -f, and practical examples for processing delimited formats like CSV and system configuration files.

The Role of the cut Command in Linux

In Linux text processing, the cut command functions as a column-based filter. Unlike commands that filter entire lines (such as grep), cut slices out vertical segments from each line of a file or standard input. It is particularly useful when working with tabular or delimited text, allowing administrators and developers to isolate specific columns of data without relying on heavier processing tools like awk or sed.

Syntax for Extracting Fields

To extract fields using cut, two primary options are used together:

cut -d '<delimiter>' -f <field_numbers> <filename>

Specifying Delimiters with -d

Text files use various characters to separate data columns. The -d option defines which character acts as the boundary.

Note: The standard cut utility only supports single-byte delimiters. It cannot use regular expressions or multi-character strings as delimiters.

Selecting Fields with -f

The -f option provides flexible ways to target single fields, lists of fields, or ranges:

When extracting multiple fields, cut preserves their original order from the file and separates them in the output using the defined input delimiter (unless modified by --output-delimiter).

Useful Modifiers for Field Extraction

Complementing Selections (--complement)

To display every field except the ones specified, use the --complement flag.

cut -d ',' -f 2 --complement data.csv

This prints all fields except the second field.

Suppressing Lines Without Delimiters (-s)

By default, if a line in the input does not contain the specified delimiter, cut prints the entire line unchanged. Adding the -s (or --only-delimited) flag forces cut to skip any line that lacks the delimiter, preventing headers or commentary lines from polluting the output:

cut -d ':' -s -f 1 /etc/passwd

Changing the Output Delimiter (--output-delimiter)

You can transform data formatting during extraction by defining a different character for the output:

cut -d ':' -f 1,7 --output-delimiter=' -> ' /etc/passwd

This prints the username and default shell separated by -> instead of a colon.

Using cut in Shell Pipelines

The primary strength of cut lies in command pipelines. It accepts input directly from stdin, making it efficient for extracting data on the fly:

cat /var/log/auth.log | grep "Failed password" | cut -d ' ' -f 1-3

By isolating exact fields quickly and with minimal CPU overhead, the cut command remains a fundamental utility for log analysis, CSV parsing, and shell script automation in Linux.