Cut Command in Unix with Examples

The cut command extracts a given number of characters or columns from a file. For cutting a certain number of columns it is important to specify the delimiter. A delimiter specifies how the columns are separated in a text file

Example: Number of spaces, tabs or other special characters.

Syntax:

cut [options] [file]
The cut command supports a number of options for processing different record formats. For fixed width fields, the -c option is used.



$ cut -c 5-10 file1
This command will extract characters 5 to 10 from each line.

For delimiter separated fields, the -d option is used. The default delimiter is the tab character.

$ cut -d “,” -f 2,6 file1
This command will extract the second and sixth field from each line, using the ‘,’ character as the delimiter.

Example:

Assume the contents of the data.txt file is:

Employee_id;Employee_name;Department_name;Salary
10001;Employee1;Electrical;20000
10002; Employee2; Mechanical;30000
10003;Employee3;Electrical;25000
10004; Employee4; Civil;40000

And the following command is run on this file:

$ cut -c 5 data.txt
The output will be:

o
1
2
3
4
If the following command is run on the original file:

$ cut -c 7-15 data.txt
The output will be:

ee_id; Emp
Employee1
Employee2
Employee3
Employee4
If the following command is run on the original file:

$ cut -d “,” -f 1-3 data.txt
The output will be:

Employee_id;Employee_name;Department_name
10001;Employee1;Electrical
10002; Employee2; Mechanical
10003;Employee3;Electrical
10004; Employee4; Civil