Skip to content

cut command-How to extract text by column or field

October 3, 2023
Linux

This article provides a step-by-step guide on how to extract text by column or field using the cut command, a powerful command-line tool.

Extracting Text by column or Field cut

  • Display specific columns of file or STDIN data
cut -d: -f1 /etc/passwd
grep root /etc/passwd | cut -d: -f7
  • Use -d to specify the column delimiter (default is TAB)
  • Use -f to specify the column to print
  • Use -c to cut by characters
cut -c2-5 /usr/share/dict/words

cut is used to “cut” fields or columns of text from a file and display it to standard output.

For example:

cut -f3 -d: /etc/passwd

will display a list of UIDs from /etc/passwd, because UIDs are stored in the third colon-delimited field.

A slightly more complicated example shows how cut can be used with other tools to extract a single piece of information, in this case the system’s IP addresses, from a larger block of output. After examining the command and output below try running /sbin/ip a by itself and see if you can piece together what each step of the pipeline does:

/sbin/ip a | grep 'inet ' | cut -d " " -f6 | cut -d / -f1

output

192.168.0.254
127.0.0.1

What is STDIN DATA?


STDIN data is the data that is read by a program from its standard input stream. The standard input stream is typically connected to the keyboard, but it can also be connected to a file or another device.

To read STDIN data, a program typically uses the read() system call. The read() system call reads a specified number of bytes from the standard input stream and stores them in a buffer. The program can then access the data in the buffer to process it.

STDIN data is often used to provide input to a program interactively. For example, a program that asks the user for their name would read the user’s name from STDIN. STDIN data can also be used to provide input to a program from a file. For example, a program that processes a list of names might read the list of names from a file on disk.

Here are some examples of how STDIN data is used in programs:

  • A shell program that prompts the user for a command and then executes the command reads the command from STDIN.
  • A text editor that allows the user to type text into a file reads the text from STDIN.
  • A program that compresses or decompresses files reads the input file from STDIN and writes the output file to STDOUT.
  • A program that filters text reads the input text from STDIN and writes the filtered text to STDOUT.

STDIN data is a powerful way to provide input to programs. It allows programs to be interactive, to process files, and to be used in pipelines of other programs.