Unix Cut Command Tutorial
The Unix "cut" command is used to locate and cut characters or fields from an input file. Unlike the "cut" command in Windows programs, "cut" does not actually remove characters or fields from the file, but simply locates and reports them. "Cut" is a basic command which any user able to operate in the shell environment should be able to master.
Instructions
-
-
1
Use the basic cut command with the syntax:
cut [options] [file]
If no options are specified, the cut command will split the contents of each line using a default delimiter based on settings in the shell.
-
2
Use the character list option, -c, to specify a single position, multiple positions or a range of positions of characters to be cut. For example:
To cut the first, third and fifth characters in each line in the file "file.txt":
cut -c 1,3,5 file.txt
To cut all characters up to the fifth character:
cut -c 1-5 file.txt
To cut all characters from the fifth to the end of each line:
cut -c 5- file.txt
Use the same syntax to specify bytes to cut when using the byte list option, -b.
When using either the -c or -b option, tabs and backspaces are treated like any other character and take up only one character or one byte.
-
-
3
Specify fields to be cut using the field list option, -f. For example:
To cut the first two fields in each line of file.txt:
cut -f 1,2 file.txt
When used without flags to direct it, fields will be cut using the shell's default delimiter, which is stored in the shell variable IFS. IFS is typically the tab character, unless otherwise set.
-
4
Set the delimiting character on which fields should be cut using the delimiter option, -d. The delimiting character may be any character you specify. Enclose the delimiting character in quotes if it might otherwise be ambiguous, or use a leading backslash to specify special characters. For example:
To specify comma (,) as the default delimiter:
cut -d ',' file.txt
To specify the tab as the default delimiter:
cut -d \t file.txt
Combine the field list and delimiter options to make best use of the cut command to select fields. For example, to select the first three fields of a line of fields separated by single spaces:
cut -d ' ' -f 1-3 file.txt
-
1
Tips & Warnings
View the UNIX manual page for the cut command for information on other options and for more examples. Additional options are available to ignore lines that do not contain the delimiting character, to specify a delimiter for use between fields of output, and to prevent multibyte characters from being split.
Only single characters may be used as delimiters. You may not use regular expressions to specify complex cutting patterns.
References
Resources
- Photo Credit scissor cut image by Jakub Cejpek from Fotolia.com