The cut
command in Linux is used to extract specific sections from each line of a file or input. This is useful for processing text files and data streams where you need to isolate particular fields or characters.
Initial Example
Using cut
to extract the first 5 characters from each line of a file called example.txt
:
cut -c 1-5 example.txt
CUT Parameters
Parameter | Description |
---|---|
-b, --bytes=LIST | Select only the specified bytes from each line. |
-c, --characters=LIST | Select only the specified characters from each line. |
-d, --delimiter=DELIM | Use DELIM as the field delimiter instead of the default TAB. |
-f, --fields=LIST | Select only the specified fields; also print lines with no delimiter unless -s is specified. |
-n | Ignored option (included for compatibility). |
--complement | Complement the selection, choosing all but the specified bytes, characters, or fields. |
-s, --only-delimited | Do not print lines that do not contain delimiters. |
--output-delimiter=STRING | Use STRING as the output delimiter; default is the input delimiter. |
-z, --zero-terminated | Use NUL instead of newline as the line delimiter. |
--help | Display help information and exit. |
--version | Show version information and exit. |
Examples
1. Extract Specific Character Positions
To extract specific character positions from each line of a file:
cut -c 1-5 filename.txt
2. Extract Fields Separated by a Delimiter
To extract specific fields from each line of a file, using a delimiter (e.g., comma):
cut -d ',' -f 1,3 filename.txt
3. Extract Fields by Tab Delimiter
To extract fields separated by tabs (the default delimiter):
cut -f 2 filename.txt
4. Extract a Range of Fields
To extract a range of fields (e.g., from the second to the fourth field):
cut -d ',' -f 2-4 filename.txt
5. Extract Fields Using a Different Delimiter
To extract fields using a custom delimiter (e.g., semicolon):
cut -d ';' -f 1,2 filename.txt
6. Combine Options
To combine options for more complex extraction, such as extracting the first three characters and the second field separated by a comma:
cut -c 1-3 -d ',' -f 2 filename.txt