How to Use the cut Command in Linux: Syntax and Examples
The
cut command in Linux extracts sections from each line of input based on bytes, characters, or fields. Use options like -b for bytes, -c for characters, and -f with -d to specify fields separated by delimiters.Syntax
The basic syntax of the cut command is:
cut [OPTION]... [FILE]...
Common options:
-b LIST: Select only bytes from each line.-c LIST: Select only characters from each line.-f LIST: Select only fields (columns) from each line.-d DELIM: Use DELIM as the field delimiter (default is tab).
The LIST specifies which bytes, characters, or fields to extract. It can be a single number, a range (e.g., 1-4), or a comma-separated list (e.g., 1,3,5).
bash
cut -b LIST [FILE] cut -c LIST [FILE] cut -f LIST -d DELIM [FILE]
Example
This example shows how to extract the first 5 characters from each line of a file named sample.txt. It also shows how to extract the second field separated by a comma.
bash
echo -e "apple,red\nbanana,yellow\ncherry,red" > sample.txt cut -c 1-5 sample.txt cut -f 2 -d , sample.txt
Output
apple
banan
cherr
red
yellow
red
Common Pitfalls
Common mistakes when using cut include:
- Using
-fwithout specifying the correct delimiter with-d, which defaults to tab. - Confusing byte positions (
-b) with character positions (-c), especially with multibyte characters. - Not quoting or escaping special characters in delimiters.
Example of wrong and right usage:
bash
echo "one,two,three" | cut -f 2 # Output is empty because default delimiter is tab echo "one,two,three" | cut -f 2 -d , # Correct output: two
Output
two
Quick Reference
| Option | Description | Example |
|---|---|---|
| -b LIST | Select bytes | cut -b 1-3 file.txt |
| -c LIST | Select characters | cut -c 1-5 file.txt |
| -f LIST | Select fields | cut -f 2 -d , file.csv |
| -d DELIM | Set field delimiter | cut -f 1 -d : file.txt |
Key Takeaways
Use
-f with -d to extract specific fields separated by a delimiter.Use
-c to extract characters and -b to extract bytes carefully, especially with multibyte characters.Always specify the delimiter with
-d when using -f if your data is not tab-separated.Ranges and lists can be combined in the
LIST argument, like 1-3,5,7.Test your command on sample data to avoid unexpected empty output.