The cut
command is a Unix utility used for extracting specific sections (columns) of lines from files or standard input. It is particularly useful when dealing with structured text data that is delimited by a common character, such as tabs or spaces. cut
allows you to define the delimiter and specify the fields (columns) to extract. Here's a detailed explanation of the cut
command with examples:
Basic Syntax:
cut [options] [file]
options
: Optional flags to control the behavior ofcut
.[file]
: The input file to process. If not provided,cut
reads from standard input.
Common Options:
-
-f
or--fields
: Specifies the field(s) to extract. Fields are separated by the delimiter.- Example:
-f 1,3
extracts the first and third fields.
- Example:
-
-d
or--delimiter
: Specifies the delimiter character that separates fields. The default delimiter is the tab character (\t
).- Example:
-d ,
specifies a comma as the delimiter.
- Example:
-
-c
or--characters
: Specifies the character(s) or byte range to extract.- Example:
-c 1-5
extracts characters 1 through 5.
- Example:
-
-s
or--only-delimited
: Suppresses lines that do not contain the delimiter character.
Examples of cut
Usage:
-
Extracting Fields from a CSV File:
- Extract the first and third fields from a CSV file.
cut -d ',' -f 1,3 data.csv
-
Extracting Characters from a Text File:
- Extract characters 1 to 5 from each line of a file.
cut -c 1-5 file.txt
-
Extracting Fields from a TSV (Tab-Separated Values) File:
- Extract the second field from a TSV file.
cut -f 2 data.tsv
-
Extracting Fields with a Different Delimiter:
- Extract the second field from a colon-separated file.
cut -d ':' -f 2 file.txt
-
Suppressing Non-Delimited Lines:
- Extract the second field from lines that contain a delimiter.
cut -d ':' -f 2 -s file.txt
-
Extracting Columns from
ps
Output:- Extract the process ID (PID) and command columns from the
ps
command output.
ps aux | cut -d ' ' -f 1,11
- Extract the process ID (PID) and command columns from the
-
Extracting Users from
/etc/passwd
:- Extract the usernames from the
/etc/passwd
file (assuming the usernames are in the first field).
cut -d ':' -f 1 /etc/passwd
- Extract the usernames from the
-
Extracting Hostnames from
grep
Output:- Extract the hostnames from the output of a
grep
command.
grep "Host:" log.txt | cut -d ' ' -f 2
- Extract the hostnames from the output of a
-
Extracting IP Addresses from Log Files:
- Extract IP addresses from log files (assuming IPs are space-separated in the second field).
cut -d ' ' -f 2 access.log
-
Extracting Fields with Variable-Length Delimiters:
- Extract the third field from lines with variable-length delimiters (using a comma or colon).
cut -d ',' -f 3 data.txt cut -d ':' -f 3 data.txt
cut
is a simple yet versatile command for extracting specific columns or characters from text data. It is commonly used in combination with other Unix utilities such as grep
, awk
, and sort
to process and manipulate structured data efficiently.