The cut command extracts data between character locations or columns. You can specify the delimiter that separates each column. In the cut terminology, each column is known as a field.
- The -f option defines the fields to extract:
cut -f FIELD_LIST filename
FIELD_LIST is a list of columns that are to be displayed. The list consists of column numbers delimited by commas. Consider this example:
$ cut -f 2,3 filename
Here, the second and the third columns are displayed.
- The cut command also reads input from stdin.
Tab is the default delimiter for fields. Lines without delimiters will be printed. The -s option will disable printing lines without delimiter characters. The following commands demonstrate extracting columns from a tab delimited file:
$ cat student_data.txt
No Name Mark Percent
1 Sarath 45 90
2 Alex 49 98
3 Anu 45 90
$ cut -f1 student_data.txt
No
1
2
3
- To extract multiple fields provide multiple field numbers separated by commas, using the following options:
$ cut -f2,4 student_data.txt
Name Percent
Sarath 90
Alex 98
Anu 90
- The --complement option will display all the fields except those defined by -f. This command displays all fields except 3:
$ cut -f3 --complement student_data.txt
No Name Percent
1 Sarath 90
2 Alex 98
3 Anu 90
- The -d option will set the delimiter. The following command shows how to use cut with a colon-separated list:
$ cat delimited_data.txt
No;Name;Mark;Percent
1;Sarath;45;90
2;Alex;49;98
3;Anu;45;90
$ cut -f2 -d";" delimited_data.txt
Name
Sarath
Alex
Anu