Cut Command examples

“Cut” Command is a utility for cutting sections from each line of the Files. It can be used to cut parts of a line by byte position, character, and delimiter. It can also be used to cut data from file formats like CSV. Let’s see some cut command examples to better understand it.

Cut Command examples
Sadly, you can’t use the cut command to cut out negativity from your life but there better ways to do that. This pic is taken from unsplash as it has no copyright

Examples

Cut the characters using the position

Specify byte position using the option -b and it will show only that letter, I am using the letter Justgeek as example.

If you want to display only the first letter i.e. J

[justgeek]# echo "JustGeek" | cut -b 1
J

To display multiple letters for example J, S, G. You need to mention the position of the character separated by a comma (,)

[justgeek]# echo "Justgeek" | cut -b 1,3,5
Jsg

Cut based on a delimiter :

To cut using a delimiter use the -d option. This is normally used in conjunction with the -f option to specify the field that should be cut. Let’s clarify using an example.

Create a file called names.csv with the content below

Jeffery,Smith,45,London
Anthony,Evans,33,California
Charles,Jones,28,Paris

The delimiter can be set to a comma preceded with -d. Cut can then pull out the fields you want with the -f flag.

[justgeek]# cat names.csv | cut -d ',' -f 1
Jeffery
Anthony
Charles

To use multiple values in delimiter then it can be separated comma (,)

[justgeek]# cat names.csv | cut -d ',' -f 1,2
Jeffery,Smith
Anthony,Evans
Charles,Jones

If you want to display age then you can just specify position with -f. Example

[justgeek]# cat names.csv | cut -d ',' -f 3
45
33
28

To display city name.

[justgeek]# cat names.csv | cut -d ',' -f 4
London
California
Paris

If you want to change the delimiter in the display then you can use the option --output-delimiter as shown in the example below.

[justgeek]# cat names.csv | cut -d ',' -f 1,2 --output-delimiter='---'
Jeffery---Smith
Anthony---Evans
Charles---Jones

How to check the “cut” command version

 [justgeek]# cut --version
 cut (GNU coreutils) 8.22
 Copyright (C) 2013 Free Software Foundation, Inc.
 License GPLv3+: GNU GPL version 3 or later http://gnu.org/licenses/gpl.html.
 This is free software: you are free to change and redistribute it.
 There is NO WARRANTY, to the extent permitted by law.
 Written by David M. Ihnat, David MacKenzie, and Jim Meyering.

So we have tried to cover another command useful in Bash Scripting. We would like to hear from you what next to write in the comment section. Do let us know if you want to add anything in the cut command examples in the comments section.

Leave a Comment