Linux – cut Command

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.

Tutorials dojo strip



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

ParameterDescription
-b, --bytes=LISTSelect only the specified bytes from each line.
-c, --characters=LISTSelect only the specified characters from each line.
-d, --delimiter=DELIMUse DELIM as the field delimiter instead of the default TAB.
-f, --fields=LISTSelect only the specified fields; also print lines with no delimiter unless -s is specified.
-nIgnored option (included for compatibility).
--complementComplement the selection, choosing all but the specified bytes, characters, or fields.
-s, --only-delimitedDo not print lines that do not contain delimiters.
--output-delimiter=STRINGUse STRING as the output delimiter; default is the input delimiter.
-z, --zero-terminatedUse NUL instead of newline as the line delimiter.
--helpDisplay help information and exit.
--versionShow 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




Linux Playground

Scroll to Top