BASH Programming

Bash Cut Examples

You can automate the tasks in the Bash script through different commands and programs. Although you need a good knowledge of commands to create excellent Bash scripts, there are a few commands that you can use as a beginner. Cut is a simple command to extract a specific text from the file.

Cut is a versatile command that you can use with other commands including the “sort” and “grep” commands. Let’s look at some of the best Bash cut examples by which you can understand the “cut” command without hassle.

Bash Cut Examples

The “cut” command is useful when extracting the data from a text file. Just specify the fields that you want, and it does the rest. To use it, enter the following command:

cut -d'delimiter' -f1 file.txt
  1. The “-d” option lets us input the delimiter. It is a character or a series of characters that separates the text strings. Replace the term “delimiter” with the actual delimiter.
  2. Using the “-f” option, specify which fields (column numbers) you are extracting from the file.

Let’s take an “info.txt” file for example which consists of the following set of information:

Prateek, Fiji, 26

Sean, India, 21

Joshua, Japan, 19

Now, to extract the first and third files from this file, the command will be:

Cut -d',' -f1,3 info.txt

If you have a file with a data separated by a tab, its delimiter value will be “$’\t'”.

If you need to get a range of characters from a respective field, use the “-c” option:

cut -c1-5 file.txt

Note that the “-c” option does not combine with the other options. Upon execution, it displays the output as per the given character range.

Conclusion

In Linux, “cut” is a prominent tool that you can use to extract the data from different files. Although simple, it has various uses and can be combined with many commands. This quick guide discussed some examples of the Bash cut commands. First, we explained the basic command and then discussed some advanced examples. Furthermore, you can pipeline the other commands’ output as an input in the “cut” command.

About the author

Prateek Jangid

A passionate Linux user for personal and professional reasons, always exploring what is new in the world of Linux and sharing with my readers.