cut command in Linux with examples

Configurare noua (How To)

Situatie

The cut command in linux is a command for cutting out the sections from each line of files and writing the result to standard output. It can be used to cut parts of a line by byte position, character, and field. The cut command slices a line and extracts the text. It is necessary to specify an option with a command otherwise it gives an error.

Solutie

Pasi de urmat
cut OPTION... [FILE]...

Let us consider two files having name state.txt and capital.txt contains 5 names of the Indian states and capitals respectively.

$ cat state.txt
Andhra Pradesh
Arunachal Pradesh
Assam
Bihar
Chhattisgarh

Without any option specified it displays error.

$ cut state.txt
cut: you must specify a list of bytes, characters, or fields
Try 'cut --help' for more information.
Extract Specific Bytes (-b) Using cut Command

-b(byte): 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(-). It is necessary to specify list of byte numbers otherwise it gives error.

Tabs and backspaces are treated like as a character of 1 byte.

List without ranges:

cut -b 1,2,3 state.txt

Lightbox

List with ranges:

cut -b 1-3,5-7 state.txt
list with range

It uses a special form for selecting bytes from beginning upto the end of the line:

Special Form: Selecting bytes from beginning to end of line

In this, 1- indicate from 1st byte to end byte of a line

cut -b 1- state.txt

special form

In this, -3 indicate from 1st byte to 3rd byte of a line

cut -b -3 state.txt

Tip solutie

Permanent

Voteaza

(3 din 8 persoane apreciaza acest articol)

Despre Autor

Leave A Comment?