Unix/Linux ‘cut’ command examples

Linux cut command FAQ: Can you share some cut command examples?

The Linux cut command is a really great command filter to know. You can use it to do all sorts of cool things when processing text files and text in command pipelines.

Using the cut command with /etc/passwd

For a first cut command example, I'll use the /etc/passwd file on my Unix system. I use this file because fields in the file are separated by the ":" character, which make it very easy to work with.

Using that file, here's a Linux cut command that prints the first field (first column) of every line in that file:

cut -f1 -d: /etc/passwd

This cut command can be read as:

  • Print the first field (-f1)
  • Fields are delimited by the ":" character (-d:)
  • Use the /etc/passwd file as input

The output of this command will vary by Unix and Linux systems, but it will be the first field of your /etc/passwd file, which contains the name of the users on your system. This will look something like:

nobody
alvin
george
fred

and so on.

Using the cut command in a command pipeline

You can also use cut in a Unix/Linux command pipeline. For example, although you can get this information in other ways, you can use the cut command with the ls command to get a list of filenames in the current directory, like this:

ls -al | cut -c44-

Notice that in this command I'm using the cut command "-c" option. This command can be read as:

  • Run the "ls -al" command
  • Pipe the output of that command into cut
  • The cut command prints everything from each line starting at column 44 through the end of the line (-c44-)

As you can see, the -c option lets you deal with columns or character positions. In this example I wanted all the output from each line starting in column 44 and going to the end of the line, but if I wanted only columns 40 through 50, I could have specified that like this instead:

ls -al | cut -c44-50

That particular command doesn't make much sense in the real world, since filenames can all be different lengths, but it does show how to use a range of columns with the Linux cut command.

More Unix cut command examples

There are many other uses of the Unix cut command, but I wanted to share these with you to get started. The cut command is a great Unix shell script tool, and I highly recommend being familiar with it.