Home Uncategorized Using the cut command in bash

Using the cut command in bash

by The Linux Digest Guy
Literal scissors to cut with

The cut command gives you the power to cut strings in the Linux shell or in bash scripts. Let’s look at some simple command examples.

Cut strings from a file or from another command

You can either load the text you want from a file or pipe the string from another command. To load the text from a file specify the filename as the last argument of the command.

~$ cut -f 1 file.txt 
Lots of words in a file

You can also cut the output from a command using the | operator.

$ echo "Lots of words from a command" | cut -f 1
Lots of words from a command

Cut by word

To get a particular word from a string you just need to specify a space as the delimiter using the -d argument. The -f argument specifies which word you want to get. The list of words starts from 1.

~$ echo "this is a multi word string" | cut -d ' ' -f 2
is

If you want to get more than one word, you can specify multiple words seperated by a comma.

~$ echo "this is a multi word string" | cut -d ' ' -f 2,3,4
is a multi

Cut by character position

To get the nth character from a string use the -c argument. In this example we want the fourth character from the string.

~$ echo "abcdefg" | cut -c 4
d

We can also specify a range of characters.

~$ echo "abcdefg" | cut -c 4-6
def

Or a comma seperated list

~$ echo "abcdefg" | cut -c 1,3,5
ace

I hope this short tutorial helps you to get started with the cut command.

0

Related Posts

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More

Privacy & Cookies Policy