cut is a command-line utility that allows you to cut parts of lines from specified files and print the result to standard output. It can be used to cut parts of a line by field or delimiter.
The syntax for the cut command is as follows:
$ cut OPTION... [FILE]...
Consider the file and its data:
Cut by Field: To specify the fields that should be cut, write the command with the -f option. When not specified, the default delimiter is “TAB”
To display the 1st and the 3rd field you would use:
Example:
$ cut test.txt -f 1,3
245:789 M:4540
535:763 M:3476
Or if you want to display from the 1st to the 4th field:
Example:
$ cut test.txt -f -4
245:789 4567 M:4540 Admin
535:763 4987 M:3476 Sales
To complement the selection field list use --complement option. This will print only those fields that are not selected with the -f option. The following command will print all field except the 1st and 3rd:
Example:
$ cut test.txt -f 1,3 –complement
4567 Admin 01:10:1980
4987 Sales 11:04:1978
Cut by delimiter: To cut based on a delimiter, invoke the command with the -d option, followed by the delimiter you want to use.
To display the 1st and 3rd fields using “:” as a delimiter, you would type:
Example:
$ cut test.txt -d ':' -f 1,3
245:4540 Admin 01
535:3476 Sales 11
Cut by Bytes: To cut by bytes, we’ll use the -b or –bytes option.
To print the second byte from each line in the file:
Example:
$ cut -b 2 test.txt
4
3
To cut by the 2nd, 4th, and 7th bytes simultaneously we’ll use the “,” separator:
Example:
$ cut -b 2,4,7 test.txt
4:9
3:3
We can also specify a range, using the “-“ separator:
Example:
$ cut -b 2-7 test.txt
45:789
35:763