CentOS Debian Mint openSUSE Red Hat Ubuntu

Cut command in Linux

Cut command in Linux

Introduction

Cut is a command used to extract parts of the line from files or piped data and export the result to standard output.

it’s a built-in command-line utility in Linux and UNIX systems. The cut command can cut parts of the line by byte position, field, and character.

Below is the guide on how to use the cut command in Linux.

The syntax of cut command

$ cut OPTION… [FILE]...

[options]

-b (byte) Slicing by bytes

-f (field) Slicing by fields

-c (character) Slicing by characters

-d (delimiter) Slicing by delimiter instead of TAB delimiter

–complement Complement the output

–output-delimiter Change the output delimiter

How to use cut command

1. -b (byte)

To cut out specific bytes. The range of bytes can be specified with “-”. Tabs and backspaces are also considered 1 byte.

$ cut -b [file]

For example, in hello.txt file contains the text “Hello World!”. Now we will cut out specific bytes:

$ cut -b 1 hello.txt

In the above command, they output the first character as “H

$ cut -b 1,6,7 hello.txt

In the above command, the output 1st, 6th, and 7th characters. The 6th character is an empty character.

List with ranges:

$ cut -b 1-3,7-9 hello.txt

It also selects bytes from beginning up to the end of the line through a special form:

$ cut -b 1- hello.txt

In the above command, the output from the 1st byte to the last byte.

$ cut -b -4 hello.txt

In the above command, the output from the 1st byte to the 4th byte.

2. -f (field)

To extract specific fields. When no delimiter is specified, the default delimiter will be TAB.

$ cut -f [FILE]

For example, here we have field.txt file:

Now we will extract the 1st and the 2nd field:

$ cut -f 1,2 field.txt

Output:

3. -c (character)

To cut by character. This can be a list separated by “.”, “,”, “;”; “”. Tabs and backspaces are also considered a character.

$ cut -c [FILE]

For example, here we have character.txt file:

Now we will extract the 2nd, 4th, 6th character:

$ cut -c 2,4,6 character.txt

Output:

4. -d (delimiter)

To cut out specific delimiters. This option is often used with -f (field).

For example, here we have dlmt.txt file separated by “:

Now we will extract from the 1st to the 3rd field:

$ cut -d ":" -f 1-3 dlmt.txt

Output:

5. –complement

To print all fields except those that are not selected with -f option.

For example, here we have field.txt file:

Now we will extract all fields except the 1st and 4th fields:

$ cut --complement -f 1,4 field.txt

Output:

6. –output-delimiter

To change the output delimiter. –output-delimiter=”delimiter”.

Now we will extract all fields except the 1st and 4th field but the output is separated by “?” :

& cut –complement -f 1,4 field.txt –output-delimiter=”?”

Output:

Conclusion

You’ve already gone through the details of how to use the cut command in Linux.

Thanks for reading.

Similar Posts