The cut command
The cut command is most often used to select single columns of data from input separated by a single character, such as an /etc/passwd file. For example, the cut command is used to extract specified columns/characters of a piece of text, which is given as follows:
- -c: Specifies the filtering of characters
- -d: Specifies the delimiter for fields
- -f: Specifies the field number
Cut Command Examples
The following are a few examples that show the usage of the cut command:
Let’s start with a simple example of extracting a specific column from the /etc/passwd file. As the /etc/passwd file fields are delimited with “: (colon)” delimiter, we will use the option “-d:” in the command.
# cut -d: -f6 /etc/passwd
In this example, -d specifies the delimiter or separator variable, in this case a colon, and -f specifies the number of the field (or column), starting from 1.
We can also filter out multiple columns from the /etc/passwd file using the comma separated indices. For example:
# cut -d: -f1,3 /etc/passwd
The display will contain the login name and user ID.
We can also specify the field numbers with hyphen-separated ranges. We can also combine the comma-separated indices and hyphen-separated ranges for filtering out the columns. For example:
# cut -d: -f1,3-4 /etc/passwd
We can leave one of the numbers out of a range, to mean “up to” or “from”. For example, to filter out columns “upto 2”, use the below command:
# cut -d: -f-2 /etc/passwd
Similarly, to display fields from 6 till the end, use the below command:
# cut -d: -f6- /etc/passwd
However, cut is not limited to delimited data. It can also split on character counts with -c, or bytes with -b. This can be a useful way to get only a certain number or range of bytes per line. As shown in the example below, the output of the date command is sent as an input to the cut command and only the first three characters are printed on screen, which is shown as follows:
# date | cut -c1-3 Wed
The date command without the cut command, would print an output as shown below:
# date Wed Dec 5 15:24:12 UTC 2018