DEV Community

Cover image for Bash Cut Operation
Damon Marc Rocha II
Damon Marc Rocha II

Posted on

Bash Cut Operation

As promised, here is the next addition to my bash blog series. In this article, I wanted to cover the cut operation. With knowledge of the cut operation parsing, sorting, and reading data becomes a lot easier in bash. This post covers the basics of cut and should give a good foundation to use it how you see fit.

Cut

To get the information you want from your string, data, or whatever else just follow it with | cut and the flag of your choice. The example below uses the character flag:

read line
echo $line | cut -c 3
Enter fullscreen mode Exit fullscreen mode

The command above reads in a line and then outputs the third character of whatever was input. This is done by placing the -c(character flag) after cut and then giving the placement of the character you want from the string(starting from 1). This can also be extended to cut multiple characters using either a '-' or ','. For example:

read line //=> Hello World
echo $line | cut -c 1-5 //=> Hello
echo $line | cut -c 1,5,8 //=> Hoo
Enter fullscreen mode Exit fullscreen mode

Alt Text

Cutting Flags

There are many different flags that can be used with cut other than the character flag; read more here. I want to cover two very useful flags the -d, and -f flags. The -d or the delimiter flag specifies what to cut the input on. The -f or field flag allows you to specify the index of the items you want back from what you split with the delimiter flag. These two are often used together to get back specific chunks of information.
For example:

read line //=> hi how are you
echo $line cut -d $' ' -f 1-3 //=> hi how are
Enter fullscreen mode Exit fullscreen mode

There are many more ways to use this command and other flags to explore. I would love to see any examples I missed here and hear any feedback to make this series better. Next week I will cover reading from a text file.

Top comments (0)