cut Command: Tutorial & Examples
Extract fields or columns from a file
The cut
command is a Unix and Linux command used to extract specific fields or columns from a file. It allows you to extract and display a specific range of characters or fields
from a file or standard input.
Here is the basic syntax for the cut
command:
cut -f field_list [-d delimiter] [-s] [file]
Here, field_list
is a list of fields or columns that you want to extract, separated by commas. The -d
option allows you to specify a delimiter character, such as a tab or a
comma, to use when dividing the input into fields. The -s
option tells cut
to only print lines that contain the delimiter character. file
is the name of the file that you
want to extract fields from. If no file is specified, cut will read from standard input.
For example, suppose you have a file named data.txt
with the following contents:
John Doe,42,New York
Jane Smith,37,Chicago
You could use the following command to extract the first field (the name) from each line:
cut -f 1 -d , data.txt
This would output the following:
John Doe
Jane Smith
You can specify a range of fields using a dash. For example, the following command would extract the first and second fields from each line:
cut -f 1-2 -d , data.txt
This would output the following:
John Doe,42
Jane Smith,37
Note that cut
works with fixed-width fields as well as delimiter-separated fields. You can specify the starting and ending positions of the fields that you want to extract using
the -c
option instead of the -f
option.
There are many other options and features available with the cut
command. You can learn more about cut
by reading its documentation or by using the cut --help
command.