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
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
We can also specify a range of characters.
~$ echo "abcdefg" | cut -c 4-6
Or a comma seperated list
~$ echo "abcdefg" | cut -c 1,3,5
I hope this short tutorial helps you to get started with the cut command.