The cut is a command-line utility to cut parts of lines from specified files and writing the result to standard output. It can be used to cut parts of a line by byte position, character and delimiter. In this guide, we will show you how to use cut command in Linux with examples.
How to Use the cut Command
Following is the basic syntax of Cut command:
cut OPTION... [FILE]...
The options tells cut whether to use a delimiter, byte position, or character when cutting out selected portions the lines. You can use any one option at a time out of as following:
-f (--fields=LIST)– It used when need to select by specifying a field, a set of fields, or a range of fields.
-b (--bytes=LIST)– Select by specifying a byte, a set of bytes, or a range of bytes.
-c (--characters=LIST)– Select by specifying a character, a set of characters, or a range of characters.
You also can use other options listed below:
-d (--delimiter)– To specify a delimiter as replacement of of the default “TAB” delimiter.
--complement– To display all bytes, characters, or fields except the selected.
s (--only-delimited)Prints the lines that only contain delimiter character
--output-delimiter– To specify a different output delimiter string.
How to Cut by Field
To cut the specified fields use command with the -f option. “TAB” is the default delimiter if not specified.
Y-2019 Allen K-100 NY Y-2020 John K-200 NJ
For instance, to display the 2nd and 3rd field you would use:
cut sales.txt -f 2,3
Allen K-100 John K-200
How to cut based on a delimiter
-d followed by the delimiter you want to use with cut command to cut based on a delimiter.
For example, to display the 1st and 3rd fields using
“-” as a delimiter, you would type:
cut sales.txt -d '-' -f 1,3
Y-100 NY Y-200 NJ
How to complement the selection
To complement the selection field list use
--complement option. This will print only those fields that are not selected with the -f option.
cut sales.txt -f 2,4 --complement
The above command will print all field except the 2nd and 4th:
Y-2019 100K Y-2020 200K
How to specify an output delimiter
--output-delimiter option to specify the output delimiter. For instance, to set the output delimiter to
_ you would use:
cut sales.txt -f 1,3 --output-delimiter='_'
Generally, cut command is used with the combination with other commands through piping. Below are the examples:
List of all users
getent passwd command and pass output to
cut, that will prints the 1st field using
- as delimiter.
getent passwd | cut -d '-' -f1
The output shows a list of all system users.
Display 10 most frequently used commands
In the following example, cut is used to strip the first 8 bytes from each line of the history command output.
history | cut -c8- | sort | uniq -c | sort -rn | head
You learned how to use cut command to display selected fields from files or the standard input.