When you are managing a Linux server, you will frequently encounter files that are formatted as lists or tables. The most common examples are comma-separated values (CSV) files, or system files like /etc/passwd where data is separated by colons.
If you only want to see one specific piece of information from that file—such as a list of all usernames, without the passwords, user IDs, and home directory paths attached to them—you don’t need to manually read the file. You can use the cut command to surgically slice columns of data out of any text file.
Understanding the Syntax
To use the cut command effectively on structured data, you need to use two specific flags:
-d(Delimiter): This tells Linux what character is being used to separate the columns (e.g., a comma, a colon, a space, or a tab).-f(Field): This tells Linux which specific column number you want to extract and print to the screen.
Syntax: cut -d 'delimiter' -f column_number filename
Example 1: Extracting Usernames from /etc/passwd
The /etc/passwd file contains a list of every user on your Linux system. A typical line in this file looks like this:
root:x:0:0:root:/root:/bin/bash
Notice that every piece of data is separated by a colon (:). The username is the very first item (Field 1). The home directory is the sixth item (Field 6).
If you want to extract a clean list of only the usernames, you would run:
cut -d ':' -f 1 /etc/passwd
The command will slice the file based on the colons, grab only the first column, and print a neat list of usernames to your terminal.
Example 2: Extracting Multiple Columns from a CSV
Imagine you have a file named employees.csv. The data looks like this:
John,Sales,Manager,New York
Sarah,IT,Engineer,London
The delimiter here is a comma (,). If you want to print a list showing the employee’s name (Field 1) and their city (Field 4), you can ask cut to grab multiple fields at once by separating them with a comma.
cut -d ',' -f 1,4 employees.csv
This will output:
John,New York
Sarah,London
Example 3: Extracting by Character Position
What if the file doesn’t have a clean delimiter like a comma, but instead every line is just exactly 10 characters long? You can use the -c (character) flag to slice the file strictly by character position.
If you have a file and you only want to read the first 5 letters of every line, you would run:
cut -c 1-5 filename.txt
This tells cut to grab characters 1 through 5, completely ignoring any delimiters or formatting, which is incredibly useful for parsing old legacy log files.