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
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:
Command
Output
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
Output
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:
Command
Output
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:
Command
Output
Explanation:
- The first
cut
extracts fields 1 and 3, yieldingapple,red
, etc. - The second
cut
replaces the comma delimiter with-
for custom formatting.
Summary of Common cut
Commands
Command | Description |
---|---|
cut -d ',' -f 1 file.txt | Extracts the first field from a comma-separated file. |
cut -d ':' -f 1,3 file.txt | Extracts the first and third fields with colon : as delimiter. |
cut -c 1-3 file.txt | Extracts 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.