Linux cut Command


The cut command in Linux is used to extract specific columns or fields from text data, making it useful for processing structured data like logs, CSV files, or command outputs. It operates by selecting parts of each line in a file based on delimiter-separated fields or character positions.

Basic Syntax

cut [options] filename

Common Options

  • -f : Specifies the fields to extract (works with -d for delimiter).
  • -d : Sets the delimiter character (default is tab).
  • -c : Cuts specific character positions.

Examples with Output

1. Extracting Specific Fields from a Delimited File

Suppose file.txt contains the following comma-separated data:

John,Doe,30 Jane,Smith,25 Mike,Johnson,40
Command
cut -d ',' -f 1,3 file.txt
Output
John,30 Jane,25 Mike,40

Explanation:

  • -d ',' specifies that fields are separated by a comma.
  • -f 1,3 extracts the 1st and 3rd fields from each line, skipping the 2nd field.

2. Extracting Fields from /etc/passwd

The /etc/passwd file on Linux systems contains user account information separated by colons :. Each line has fields like username, password placeholder, UID, GID, etc.

Command
cut -d ':' -f 1,3 /etc/passwd
Output
root:0 daemon:1 bin:2 sys:3

Explanation:

  • -d ':' sets the delimiter as a colon.
  • -f 1,3 extracts the 1st and 3rd fields (username and UID) from each line.

3. Extracting Specific Characters from Each Line

Assume file.txt has:

abcdef ghijkl mnopqr
Command
cut -c 1-3 file.txt
Output
abc ghi mno

Explanation:

  • -c 1-3 extracts the 1st to 3rd characters from each line, ignoring the rest.

4. Combining Fields with a Custom Delimiter

Suppose file.txt has:

apple,fruit,red banana,fruit,yellow carrot,vegetable,orange
Command
cut -d ',' -f 1,3 file.txt | cut -d ',' -f 1,2 --output-delimiter=" - "
Output
apple - red banana - yellow carrot - orange

Explanation:

  • The first cut extracts fields 1 and 3, yielding apple,red, etc.
  • The second cut replaces the comma delimiter with - for custom formatting.

Summary of Common cut Commands

CommandDescription
cut -d ',' -f 1 file.txtExtracts the first field from a comma-separated file.
cut -d ':' -f 1,3 file.txtExtracts the first and third fields with colon : as delimiter.
cut -c 1-3 file.txtExtracts characters 1 through 3 from each line.
`cut -d ',' -f 2 --output-delimiter="" file.txt`

The cut command is a quick way to isolate and format specific sections of text in files, making it invaluable for text processing and scripting in Linux.