‘CUT’ command in unix with example

Hi Guys, Hope you all are doing well.

We are back with another command in Unix which is very much needed in day to day’s work and our day cannot be completed without using it once i.e. cut command.

One can use this command to extract text from the string or file for particular columns with delimiter defined.  So basically this helps to extract desired text from file or string by cutting or slicing it.

Enough of these theories now, let’s see some practical examples.

Consider a below sample file

Sample file

  1. How to select particular column in file?

cut command can use to print or extract text from required colum from file with the help of ‘-c’. Please refer below

If anyone want to extract 3rd column/character from each line of the file,

Cut to character

  1. How to extract range of characters from each line of a file?

With some modification in above command we can get intended result as shown below

cut to range

  1. How to get entire line from a specific column or character?

To obtain this no need to provide 2nd numeric in -c option as below

cut to end

To get only first 5 characters from each line of file cut command can be modified as


cut to start

Try to use cut command without using any number and check what happens. For example – ‘cut -c- sample.txt’

  1. How to extract field instead of characters from a file?

To extract a field we need to take help of delimiter in the file.

In above sample file the delimiter defined is ‘ ‘ i.e. space. Now to get 1st field, new option can be added in cut command which ‘-d’, ‘-f’ and how? Described below

cut to delimiter

It will extract the characters till the defined delimiter appears in the each line of file.

Now to extract range or multiple fields from the file, similar to ‘-c’ option we can use ‘-‘ option to specify range. Refer below example.

cut to field

Below options can be used for different purposes.

$ cut -d’ ‘ -f2,5 sample.txt

$ cut -d’ ‘ -f-5 sample.txt

$ cut -d’ ‘ -f- sample.txt

Happy ‘Cutting’ 🙂


(Edit)

Leave a Reply

Logged as admin. Log out »

© 2017 Database ETL. All rights reserved.
Skip to toolbar Log Out