Linux cut command with examples

In this article, we will see Linux cut command with examples.

Linux command cut is used for text processing. We can use this command to extract portion of text from a file by selecting columns. It can be used to cut parts of a line by byte position, character and field.

Syntax:

cut OPTION... [FILE]...

Options:

-b: selects only these bytes -c: selects only these characters -d: uses DELIM instead of TAB for field delimiter -f: selects only these fields; --complement: complement the set of selected bytes, characters or fields --output-delimiter: uses STRING as the output delimiter the default is to use the input delimiter

We are going to perform examples on the following file employees.txt

Linux cut command with examples

Linux cut command examples

1. Cut the text by using field of Linux file.

Cut the fields 1,2 and 4 of a file.

cut -f 1,2,4 staff.txt

The above command prints the 1st, 2nd and 4th field of file staff as highlighted below.

Linux cut command with examples

2. Display fields from 2nd to 5th.

cut staff.txt -f 2-5

-b: To extract the specific bytes, you need to follow -b option with the list of byte numbers separated by comma. Range of bytes can also be specified using the hyphen(-).

3. Following command prints 5 bytes of each line from file staff.txt

cut -b 5 staff.txt

4. Following command prints from 6 byteto end of file staff.txt

cut -b 5- staff.txt

-c:To cut by character use the -c option.

5. Following cut command prints 5 character of the file staff.txt.

cut -c 5 staff.txt

6. If we want to get from 5 character of each line in Linux file, use the following command.

cut -c 6- staff.txt

7. Print the data after first delimiter onwards and up to next delimiter using delimiter(-d) option.

cut -d "-" -f 2 staff.txt

8. Get list of users in Linux by using Cut command.

getent passwd | cut -d ":" -f1

9. How to get frequently used command in Linux environment by using cut command.

history | cut -c8- | sort | uniq -c | sort -rn | head

So in this article, we have explained Cut command with examples.