How to Use cut Command in Bash: Syntax and Examples
Use the
cut command in bash to extract specific sections from lines of text by specifying delimiters with -d and fields with -f, or by character positions with -c. For example, cut -d',' -f2 file.txt extracts the second field from comma-separated lines.Syntax
The basic syntax of cut is:
cut -d 'delimiter' -f fields [file]: Extract fields separated by a delimiter.cut -c positions [file]: Extract characters by position.cut [options]: Options control how text is sliced.
Explanation:
-d: Specifies the delimiter character (default is tab).-f: Specifies which fields (columns) to extract, separated by commas or ranges.-c: Specifies character positions to extract.file: The input file; if omitted,cutreads from standard input.
bash
cut -d',' -f1,3 file.txt cut -c1-5 file.txt
Example
This example shows how to extract the second field from a comma-separated file and how to extract the first 5 characters from each line.
bash
echo -e "name,age,city\nAlice,30,New York\nBob,25,Los Angeles" > data.csv cut -d',' -f2 data.csv cut -c1-5 data.csv
Output
age
30
25
name
Alice
Bob
Common Pitfalls
Common mistakes when using cut include:
- Not specifying the correct delimiter with
-d, which defaults to tab. - Using
-fwithout-don files that are not tab-separated. - Mixing
-fand-coptions, which is not allowed. - Expecting
cutto handle multiple delimiters or complex patterns (it does not).
Wrong: cut -f2 file.csv on comma-separated file without -d','
Right: cut -d',' -f2 file.csv
bash
echo "a,b,c" | cut -f2 # Output is empty because default delimiter is tab echo "a,b,c" | cut -d',' -f2 # Output: b
Output
b
Quick Reference
| Option | Description |
|---|---|
| -d 'delimiter' | Set the field delimiter character |
| -f list | Select only these fields (columns) |
| -c list | Select only these character positions |
| --complement | Select all except the specified fields or characters |
| --help | Show help message |
Key Takeaways
Always specify the correct delimiter with -d when using -f to extract fields.
Use -c to extract characters by position, and -f to extract fields by delimiter.
Do not mix -f and -c options in the same command.
cut reads from standard input if no file is given.
cut is simple and fast but only works with fixed delimiters and positions.